4.5 类型转换
4.5 类型转换
-
由于 Java 是强类型语言,所以要进行有些运算的时候,需要用到类型转换
graph LR A(低)....->B(高) C(byte,short,char)-->D(int)-->E(long)-->F(float)-->G(double) -
运算中,不同类型的数据先转换为同一类型,然后进行运算
- 强制类型转换(高→低)
public class HelloWorld {
public static void main(String[] args) {
//强制转换
int a = 128;
byte b = (byte)a; //将 a 强制转换成 byte 类型
/*
Byte 类的 MAX_VALUE = 127
赋值 128 会出现内存溢出问题
*/
System.out.println(a);
System.out.println(b);
System.out.println("--------------------");
//精度问题
System.out.println((int)3.1415);
System.out.println((int)-3.1415f);
}
}
输出结果为:
128
-128
--------------------
3
-3
- 自动类型转换(低→高)
public class HelloWorld {
public static void main(String[] args) {
//自动转换
int c = 128;
double d = c; //将 c 自动转换成 double 类型
System.out.println(c);
System.out.println(d);
System.out.println("--------------------");
char e = 'a';
int f = e + 1;
System.out.println(f);
System.out.println((char)f);
}
}
输出结果为:
128
128.0
--------------------
98
b
- 注意点:
- 不能对布尔值进行转换
- 不能把对象类型转换为不相干的类型
- 在把高容量转换到低容量的时候,强制转换
- 转换的时候可能存在内存溢出或者精度问题
- 常见问题(溢出问题)
public class commonProblem {
public static void main(String[] args) {
//操作较大的数注意溢出问题
int myAnnualIncome = 1_000_000_000; //数字之间可以用下划线分割,且不被输出
int myAge = 17;
int total1 = myAnnualIncome * myAge;
long total2 =myAnnualIncome * myAge;
long total3 =((long)myAnnualIncome) * myAge; //先把一个数转换为 long类型
System.out.println(total1); //-179869184,溢出了
System.out.println(total2); //-179869184,默认是 int 类型,转换之前已经存在问题了
System.out.println(total3); //17000000000,没有溢出
}
}
输出结果为:
-179869184
-179869184
17000000000

浙公网安备 33010602011771号