011_JAVA基础语法_类型转换
从低到高
byte,short,char→int→long→float→double
二、类型转换
-
强制类型转换(数据类型由高容量→低容量)
-
格式:(类型)变量名
-
-
自动类型转换(数据类型由低容量→高容量)
三、注意点
-
不能对布尔值进行类型转换;
-
不能把对象类型转换为不相干的类型;
-
-
转换时要注意内存溢出、精度等问题。
//内存溢出问题
System.out.println((byte)128); //-128
//精度问题
System.out.println((int)23.7); //23
四、内存溢出实例
在操作比较大是数时注意溢出问题
//**JDK7新特性,数字之间可以使用下划线分割**
int money = 10_0000_0000;
int years = 20;
int total = money * years; //-1474836480 计算时就已经溢出
long total2 = money * years; //-1474836480 默认是int,转换之前就已经溢出?
System.out.println(total);
System.out.println(total2);
//先把一个数准换为long
long total3 = money * ((long)years);
System.out.println(total3); //20000000000

浙公网安备 33010602011771号