类型转换大小排序
根据容量由低到高的顺序依次为:byte-->short-->int-->long-->float-->double
int i = 130;
byte b = i; //报错:需要赋值byte类型
byte b = (byte)i;//内存溢出,超出范围的数字在输出时就会发现值发生了变化。
强制转换的格式
高-->低 (类型)变量名
低-->高 无需强制转换,会自动进行转换
注意事项
- 不能对boolean类型进行转换;
- 不能把对象类型转换为不相干的类型;
- 在把高容量转换到低容量的时候,强制转换;
- 转换时可能存在内存溢出活损失精度问题;
拓展应用
- char类型和int类型运算中的类型转换
char c = 'a';
int i = c+1;
System.out.println(i);//输出i的值为98
System.out.println((char)i);//输出i的值为b
- 运算中不同类型的数据先转化为统一类型,然后进行运算。
- 操作较大数时,需注意溢出问题
//JDK 7 新特性中数字之间添加下划线分割后每四个一组,对于数字的打印不会产生影响
int orderCount = 15_0000_0000;
int price = 15;
int amoutPrice = orderCount*price; //得到的结果为负数,通过计算后内存溢出,可查看int最大承载
long amountPrice1 = orderCount*price; //int*int默认int类型,已经得出溢出结果
long amountPrice2 = orderCount*(long)price; //运算前先将其中一个数转换为指定类型