JavaSE-类型转换
JavaSE-类型转换
-
由于Java是强类型语言,所以要进行有些运算时需要用到强制性转换;
-
运算中,不是同意类型的数据类型,需要转换为同一类型再进行计算;
| 低 | 高 | |||||
|---|---|---|---|---|---|---|
| byte | short | char | int | long | float | double |
自动转换
从低转到高自动转换即可
例如:
int a = 128; double c =a;//低转高,自动转账
强制转换
从高转到低需要强制转换
例如:
int a = 128;
byte b = (byte)a;//高转低,强制转换,但是会溢出
注意事项
-
不能对布尔值型进行转换
-
不能把对象类型转账为不相干的对象类型
-
高容量转账为低容量时需要强制转换
-
转换时可能存在内存溢出或是精度问题,需要小心对待;
// 内存溢出问题
System.out.println("~~~~~~~~内存溢出问题~~~~~~~~");
int money = 10_0000_0000;
int years = 20;
int total1 = money*years;//结果-1474836480,计算时已经溢出
long total2 = money*years;//默认是int值,结果已错,才去转换
long total3 = (long)money*years;//先把计算值强制转换
System.out.println(total1);
System.out.println(total2);
System.out.println(total3);//改良的代码
public class Demo04 {
public static void main(String[] args) {
System.out.println("~~~~~~~~内存溢出问题~~~~~~~~");
long money = 10_0000_0000;
int years = 20;
long total1 = money*years;
System.out.println(total1);
}
}//强制转换存在的精度问题
System.out.println((int)21.6);//输出结果21
System.out.println((int)48.899F);//输出结果48
代码
public class Demo04 {
public static void main(String[] args) {
int a = 128;
byte b = (byte)a;//高转低,强制转换
double c =a;//低转高,自动转账
System.out.println(b);
System.out.println("~~~~~~~~精度问题~~~~~~~~~~~~");
//强制转换存在的精度问题
System.out.println((int)21.6);
System.out.println((int)48.899F);
System.out.println("~~~~~~~~字符问题~~~~~~~~~~~~");
System.out.println((int)'a');
System.out.println((char)98);
System.out.println("~~~~~~~~内存溢出问题~~~~~~~~");
int money = 10_0000_0000;
int years = 20;
int total1 = money*years;//结果-1474836480,计算时已经溢出
long total2 = money*years;//默认是int值,结果已错,才去转换
long total3 = (long)money*years;//先把计算值强制转换
System.out.println(total1);
System.out.println(total2);
System.out.println(total3);
}
}
浙公网安备 33010602011771号