整型、实型(常量)、字符型数据可以混合运算。运算中,不同类型的数据先转化为同一类型,然后进行运算。
转换从低级到高级。
低 ------------------------------------> 高
byte,short,char—> int —> long—> float —> double
数据类型转换必须满足如下规则:
-
不能对boolean类型进行类型转换。
-
不能把对象类型转换成不相关类的对象。
-
在把容量大的类型转换为容量小的类型时必须使用强制类型转换。
-
转换过程中可能导致溢出或损失精度,例如:
int i =128; byte b = (byte)i; float c = 23.7; int d = (int)c; //结果 d=23
因为 byte 类型是 8 位,最大值为127,所以当 int 强制转换为 byte 类型时,值 128 时候就会导致溢出。
常见问题
//操作比较大的数时,注意的溢出问题
//Jdk7 新特性数字之间可以用下划线
int monery = 10_0000_0000;
int years = 20;
int total = monery*years;
System.out.println(total);//-1474836480 计算溢出
long total2 = monery*years; //先计算 后赋值 计算时已出现问题
System.out.println(total2);
long total3 = monery*(long)years;//先把一个数转换为Long
System.out.println(total3);