一段小程序来解释表达式中的各个数据类型的转换机制。
package com.liaojianya.chapter1;
/**
* This program demonstrates the convertion of data type.
* @author LIAO JIANYA
*
*/
public class TypeConvert6_17
{
public static void main(String[] args)
{
char ch = 'a';
short a = -2;
int b = 3;
float f = 5.3f;
double d = 6.28;
System.out.println("ch / a = " + ch / a);
System.out.println("the type of (ch / a) is : " + getType((ch / a)));
System.out.println("d / f = " + d / f);
System.out.println("the type of (d / f) is : " + getType((d / f)));
System.out.println("a + b = " + (a + b));
System.out.println("the type of (a + b) is : " + getType((a + b)));
System.out.println("(ch / a) - (d / f) - (a + b) = " + ((ch / a) - (d / f) - (a + b)));
System.out.println("the type of ((ch / a) - (d / f) - (a + b)) is : "
+ getType(((ch / a) - (d / f) - (a + b))));
}
public static String getType(Object o)
{
return o.getClass().toString();
}
public static String getType(int o)
{
return "int";
}
public static String getType(char o)
{
return "char";
}
public static String getType(short o)
{
return "short";
}
public static String getType(float o)
{
return "short";
}
public static String getType(double o)
{
return "double";
}
}
运行结果:
ch / a = -48
the type of (ch / a) is : int
d / f = 1.1849056177353188
the type of (d / f) is : double
a + b = 1
the type of (a + b) is : int
(ch / a) - (d / f) - (a + b) = -50.18490561773532
the type of ((ch / a) - (d / f) - (a + b)) is : double
分析:
1)占用字节较少的数据类型转换成占用字节较多的数据类型。
2)字符类型会转换成int类型。
3)int类型会转换成float类型。
4)表达式中出现double,则其他操作数也会转换成double类型。
5)总结:大鱼吃小鱼:占字节多的替换占字节少的;精度高的优先;优先级排序:byte,short,int,long,float,double。