- 由于Java是强类型语言,所以在进行一些运算的时候,需要用到类型转换;
- 不能对 boolean 进行转换;
- 转换的时候可能存在内存溢出的问题,或者是精度的问题;
public class Demo04 {
public static void main(String[] args) {
double f = -10.71;
int e = (int)f;
System.out.println(e);//-10
}
}
低---------------------------------------------------------->高
byte,short,char —> int —> long —> float —> double
运算中,不同类型的数据先转换为一类,再进行运算;
- 强制转换:高—>低
- 自动转换:低—>高
public class Demo04 {
public static void main(String[] args) {
byte b = 127;
int a = b;
System.out.println(a);//自动转换
int c = 100;
byte d = (byte)c;
System.out.println(d);//强制转换
}
}
操作比较大 的数字的时候,注意内存溢出的问题;
- JDK7新特性,数字之间可以用下划线隔开,这样便于观察;
public class Demo05 {
public static void main(String[] args) {
int money = 10_0000_0000;
int years = 20;
int total = money * years;
System.out.println(total);//-1474836480 内存溢出
long total2 = money * years;
System.out.println(total2);//-1474836480 还是内存溢出 因为money和years默认都是int类型的变量 他们的计算值money * years也是int int再次转换为long也是错的
//正确写法
long total3 = money *(long)years;
System.out.println(total3);//20000000000
long money3 = 10_0000_0000L;
long years3 = 20L;
long total4 = money3 * years3;
System.out.println(total4);//20000000000
}
}