类型转换
-
java是强类型语言,要进行有些运算的时候,需要用到类型转换。
低-----------------------------------------------高
byte,short,char->int->long->float->double
-
运算中,不同类型的数据先转化为同一数据类型,然后进行运算。
-
强制类型转换
int i = 128; byte b = (byte)i; //内存溢出 //强制转换 (类型)变量名 高--低 System.out.println(i); System.out.println(b);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-kyBr431D-1646818958261)(C:\Users\邢志远\Desktop\图片\6BPH_$_9@V3~FHX]DC0DBOU.png)]
-
自动类型转换
//自动转换 低--高 int j = 128; double a = j; System.out.println(j); System.out.println(a);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fr03nBe1-1646818958262)(C:\Users\邢志远\Desktop\图片\1.png)]
-
注意点
1.不能对布尔值进行转换 2.不能把对象类型转换为不相干的类型 3.在把大容量转换为低容量时,强制转换 4.转换的时候可能出现内存溢出或者精度问题
System.out.println((int)23.7);//23 System.out.println((int)-45.89f);//-45
//操作较大的数时,注意溢出问题 //JDK7新特性,数字之间可以用下划线分割 int money = 10_0000_0000; System.out.println(money); int years = 20; int total = money*years; System.out.println(total);//-1474836480 计算的时候溢出了 long total2 = money*years;//默认是int类型,先计算后转换为long,结果仍未 -1474836480 System.out.println(total2); long total3 = money*((long)years);//20000000000 System.out.println(total3);