类型转换
1.强制转换:(类型)变量名 高->低
2.自动转换 低->高
int i = 128;
byte b = (byte) i; //强制转换 byte范围最大127 内存溢出
double c = i; //自动转换
System.out.println(i); //输出128
System.out.println(b); //输出-128
System.out.println(c); //输出128.0
注意
-
不能对布尔值进行转换
-
不能把对象类型转换为不相干的类型
-
在把高容量转换为低容量的时候,强制转换
-
转换的时候可能存在内存溢出或者精度问题
System.out.println((int) 23.7); //输出 23
System.out.println((int) -45.89f); //输出 -45
char c = 'a';
int d = c + 1;
System.out.println(d); //输出 98
System.out.println((char) d); //输出 b
数字较大时
-
可用下划线
-
注意溢出问题
int money = 10_0000_0000;
System.out.println(money); //输出1000000000 自动去掉下划线
int years = 20;
int total = money * years;
System.out.println(total); //输出 -1474836480 溢出
long total2 = money * years;
System.out.println(total2); //仍输出 -1474836480
long total3 = money * ((long) years);
System.out.println(total3); //输出20000000000