朗读本文
[上]JAVA学习系列模块二第四章43.强转注意事项1_精度损失和数据溢出
视频
笔记:强转的注意事项
1.不要随意写成强转的格式,因为会有精度损失问题以及数据溢出现象,除非没有办法
2.byte,short定义的时候如果等号右边是整数常量,如果不超出byte和short的范围,不需要我们自己强转,jvm自动转型
byte,short如果等号右边有变量参与,byte和short自动提升为int,然后结果再次赋值给byte或者short的变量,需要我们自己手动强转
3.char类型数据如果参与运算,会自动提升为int型,如果char类型的字符提升为int型会去ASCII码表(美国标准交换代码)范围内去查询字符对应的int值,如果在ASCII码表范围内没有对应的int值,回去unicode码表(万国码)中找
public class Demo11DataType{ | |
public static void main(String[] args){ | |
//精度损失 | |
int i = (int)2.9; | |
System.out.println(i); | |
/* | |
数据溢出 | |
int型占内存4个字节,4个字节变成二进制是32位 | |
100个亿: 10 0101 0100 0000 1011 1110 0100 0000 0000 -> 34位二进制 | |
100个亿的二进制位比int型的二进制位多出来2位,此时干掉最前面的2位 | |
101 0100 0000 1011 1110 0100 0000 0000 | |
101 0100 0000 1011 1110 0100 0000 0000->1410065408 | |
*/ | |
int j = (int)10000000000L; | |
System.out.println(j);//1410065408 | |
System.out.println("========================="); | |
byte b = 10; | |
System.out.println(b); | |
b = (byte)(b+1); | |
System.out.println(b); | |
System.out.println("========================="); | |
char c = '中'; | |
System.out.println(c+0);//20013 | |
} | |
} |