1.定义及分类
2.注意点
- 不能对布尔值进行转换
- 不能把对象类型转换为不相干的类型
- 在把高容量转换到低容量的时候,强制转换
- 转换的时候可能存在内存溢出,或者精度问题
3. 常见转换示例
public class Demo03 {
public static void main(String[] args) {
int i = 128;
byte b = (byte)i; //内存溢出-128,加括号表示强制类型转换
double de = i; //自动类型转换
System.out.println(i);
System.out.println(b);
System.out.println(de);
System.out.println((int)23.7);
System.out.println((int)-45.89f);
char c = 'a';
int d = c +1;
System.out.println(d);
System.out.println((char)d);
}
}
执行结果:
128
-128
128.0
23
-45
98
b
4.内存溢出问题
public class Demo03 {
public static void main(String[] args) {
//操作比较大数的时候,注意溢出问题
//JDK7新特性,数字之间可以用下划线分割
int meney = 10_0000_0000;
System.out.println(meney);
int years = 20;
int total = meney*years; //-1474836480,计算的时候内存溢出了
long total2 = meney*years; //默认是int,转换之前已经存在问题了
long total3 = meney*((long)years); //先把一个数转换为long
System.out.println(total);
System.out.println(total3); //l和L区别,尽量多用L
}
}
结果:
1000000000
-1474836480
20000000000