5.类型转换
类型转换
-
由于java是强类型的语言,所以有些运算要用到类型转换。
-
在运算中,不同类型的数据会先转化为同一类型,然后进行运算。
-
在容量中,小数的容量会比整数大。
容量:低-----------------------------------------------高
byte , short , char , int-> long -> float -> double
1、强制转换
int i = 128;
//byte b = i; //这样会报错。因为高容量转换低容量要进行 强制转换。
byte b = (byte)i; //(byte) 就是强制转换符。
System.out.println(i);
System.out.println(b); //output -128.超出byte容量, 这是 内存溢出 的问题。
//在转换时,要避免内存溢出。
//强制转换->(类型)变量名。 用于容量 高-->低。
2、自动转换
//自动转换-> 用于容量 低->高。
int o = 199;
double k = o;
System.out.println(o);
System.out.println(k); //output 199.0
//运行正常,因为是从低容量转换为高容量,不需要进行强制转换。
3、精度问题
System.out.println((int)23.7); //output 23
System.out.println((int)-45.89f);
//output -45 ,在强制把小数转换为整数中出现的 精度问题。
//在强制转换中,要注意不要把小数转换为整数,否则会出现精度问题。
4、溢出问题
//操作比较大的数,注意溢出问题。
//JDK7新特性,数字之间可以用下划线分割。
int money = 1_000_000_000;
int years = 20;
int total = money*years;
System.out.println(total);
//output -1474836480. why? 计算的时候溢出int的内存范围了。
long total2 = money*years;
//等号右边是int相乘,所以结果还是int类型,要进行强制转换来改变等号右边的类型。
System.out.println(total2); //output -1474836480.
//下面开始强制转换。
long total3 = money*(long)years;
System.out.println(total3); //output 20000000000.
long total4 = (long)money*years;
System.out.println(total4); //output 20000000000.
//强制转换后,结果输出正常。在上面,强制转换money或者years获得的结果一致。表示只需要把int*int类型转换为int*long类型即可完成正常输出。
5、类型转换注意点
-
不能对布尔值进行转换,因为布尔值是表示是非。
-
-
在把高容量转换为低容量的时候,要进行强制转换。
-
转换的时候可能出现内存溢出的问题,出现在高容量转换为小容量时。
-
转换时可能会出现精度问题,出现在小数转换为整数的过程中。
浙公网安备 33010602011771号