java数据类型转换
1、强制类型转换 (类型)变量名 高–低
// byte、short、char --> int --> long --> float --> double
public static void main(String[] args) {
int i = 128;
byte b = (byte)i; // 内存溢出
}
2、自动转换 低–高
// byte、short、char --> int --> long --> float --> double
public static void main(String[] args) {
int i = 128;
Double = i;
}
3、注意点
(1)不能对布尔值进行强制类型转换
(2)不能把对象类型转换为不相干的类型
(3)在把高容量转换为低容量的时候,强制转换
(4)转换的时候可能出现内存溢出,或精度问题
4、操作比较大数据时注意内存溢出
public static void main(String[] args) {
int money = 10_0000_0000;
int years = 20;
int total1 = money * years; //-1474836480 内存溢出
long total2 = money * years; //-1474836480 默认是int,转换之前就已经存在问题了
long total3 = money * (long)years; //-1474836480 内存溢出
System.out.println(total3);
}