类型转换
- Java是强类型语言,在使用的时候会用到类型转换
- byte,short,char–>int—>long---->float---->double
- 运算中不同类型先转换为同一类型,再进行计算
- 类型转换分为
public class TypeConvert {
public static void main(String[] args) {
int i = 128;
byte b = (byte) i;
System.out.println(b);//-128,因为byte最大值127,内存溢出
/*
* 强制类型转换:高到低
* 自动类型转换:低到高*/
/*
注意点:
1.不能对布尔值进行转换
2.不能把对象类型转换成不想干的类型
3.转换是可能会出现内存溢出,和精度问题
*/
//精度问题
System.out.println("=======================");
System.out.println((int)23.7);//23
System.out.println((int)-23.753);//-23
//字符转换
System.out.println("=======================");
char c1 = 'a';
int i2 = c1+1;
System.out.println(c1);//a
System.out.println(i2);//98
System.out.println((char) i2);//b
System.out.println("=======================");
//内存溢出和解决办法
int money = 1_000_000_000;
int year = 30;
int total1 = money*year;//内存溢出
long total2 = money*year;//运算之后转换
long total3 = money*(long)year;//在运算之前强制转换
System.out.println(total1);//-64771072
System.out.println(total2);//-64771072
System.out.println(total3);//30000000000
}
}