JAVA类型转换
类型转换
低-->高
byte,short,char-> int -> long -> float -> double
1.强制转换:高-->低
public class hello {
public static void main(String[] args) {
int i = 128;
//byte最大值为127
byte b = (byte) i; //出现内存溢出
//括号里的为强制转换
//书写格式: (转换类型)变量名 高——》低
System.out.println(i);
System.out.println(b);
}
}
最后控制台输出
128 -128
2.自动转换:低-->高
public class hello {
public static void main(String[] args) {
int i = 128;
double b = i;
//从低到高不需要转换
System.out.println(i);
System.out.println(b);
}
}
最后控制台输出
128 128.0
注意点:
-
不能对布尔值尽享转换
-
不能把对象类型转换为不相干的类型
-
在把高容量转换为低容量的时候需要强制转换
-
转换的时候可能出现内存溢出,精度问题
精度问题
System.out.println((int) 12.3);
System.out.println((int) -45.234F);
最后控制台输出
12 -45
强制转换例子:
public class hello {
public static void main(String[] args) {
char i = 'a';
int d = i + 1;
System.out.println(d);
System.out.println((char) d); //强制转换char
}
}
最后控制台输出
98 b
计算溢出
public class hello {
public static void main(String[] args) {
int money = 10_0000_0000;
int years = 20;
int total = money*years; //total输出为:-1474836480
long total1 = money*((long)years);
System.out.println(total);
System.out.println(total1); //total1输出为:20000000000
}
}
int取值范围是从-2147483648 至 2147483647
//在计算时
int total = money*years;
//出现溢出:-1474836480
//因此需要将long强制转换
long total1 = money*((long)years);

浙公网安备 33010602011771号