强制转换
什么是强制转换?
-
将一个float类型转为int类型
那一个float 类型转为double类型也叫强制转换吗?
-
不是的
不同的数据类型之间的容量存在高低的关系
低 -------------------------> 高 byte --> short --> char --> int --> long --> float ----> double
强制转换只用于高容量转向低容量(高 ---> 低)
eg: int i = 123 ;
short a = (short) i ;
将 i 转为 short 类型的变量则将 short 括起来放在 i 前面,其他的强制转换也与之相同
而低精度转到高精度则可自动转换(低 ---> 高)
eg : int i = 123 ;
double a = i ;
此外boolean类型数据不能进行强制转换
此外 转换时可能出现内存溢出或者精度的问题
public class Test { public static void main(String[] args){ int money = 1000000000; int years = 20; int total = money*years; long total2 = money*years; /* 按理说,自动转换以后,total2应该为20000000... 从高向下自动转换的规则没错,则momey*years出现了错误 */ long total3 = money*(long)years; //我们在计算前就将years转换为long型的变量,结果才回复正常 System.out.println(total); System.out.println(total2); System.out.println(total3); } } //这便是内存溢出错误