一、由于Java是强类型语言,所以要进行有些运算的时候,需要用到类型转换.
低-------------------------------------------------------高
byte,short,char-> int -> long -> float -> double
注意点:
1.不能对布尔值进行转换;
2.不能把对象类型转换为不相干的类型;
3.在把高容量转换到低容量的时候,强制转换;
4.转换的时候可能存在精度问题。
下面我们来看看实例:
public static void main(String[] args) {
int i = 128;
byte b = (byte)i;//内存溢出
double c = i;
//强制转换 (类型)变量名 高--低
//自动转换 低--高
System.out.println(i);
System.out.println(b);
System.out.println(c);
}
运行结果
二、大数运算
int money = 10_0000_0000;//JDK 新特性,数字之间可以用下划线分割
int year = 20;
int total = money*year;
long total2 = money*year;
System.out.println(total);
System.out.println(total2);
运行结果
我们发现结果都是-1474836480,而不是200_0000_0000,这是因为total溢出了,而total2虽然是long类型,但它在total2转换之前money和year仍是int类型,所以我们可以将money或year转换为long类型即可获得正确结果:
long total3 = (long)money*year;
System.out.println(total3);
运行结果