数据类型转换分为强制转换和自动转换
在低位向高位转换时是自动转换
在高位向低位转换时是需要强制转换
byte 1字节 --> short char 2字节 -->int 4字节 -->long 8字节-->float 4字节
强制转换时,需要注意一些问题:
- 转换时,数据可能会溢出
- 浮点数转换成整数型时,会出现精度问题
- 浮点数范围大于整形,浮点数是1bit符号位,8位指数位,23位尾数位,指数位决定了范围,尾数位决定精度。整形1bit符号位,31位实际数字。
int i=128;
byte b = (byte)i;//高位向低位转换,溢出
System.out.println(b);//-128
double d =i;//直接赋值
System.out.println(d);//输出
System.out.println((int)23.5F);//强转int,忽略小数点后面的,23
System.out.println((int)-23.5);//强转int(double),忽略小数点后面的,-23
System.out.println("=========================================");
char c = 'a';
int i2 = c+1;
System.out.println(i2);//98
System.out.println((char)i2);//a 后面是 b
System.out.println("=========================================");
int money = 10_0000_0000;//JDK7中的新特性,C#中也有类似的特性,方便数位数了
int year = 20;
int total = money * year;
System.out.println(total);//溢出-1474836480,成负数了
long total2 = money * year;
System.out.println(total2);//溢出-1474836480计算时,已经出现问题了,结果用long接受,也是那个负值
long total3 = (long)money* year;
System.out.println(total3);//正确 20000000000计算时,将一个数字转换成long,整体自动都变成long,最后结果就对了