JAVA基础入门
四、JAVA类型转换
·由于java是强类型语言,所以要进行有些运算时,需要用到类型转换。
类型由低到高排序为:
低--------------------------------------------- 高
byte,short,char -> int -> long -> float -> double
强制转换(高转低):
格式:(类型)变量名
int i = 127;
byte b = (byte)i;
System.out.println(b);//127
自动转换(低转高):
byte c = 1;
int d = c;
System.out.println(d);//1
byte类型会自动转换为int类型
浮点数转换为整形:
System.out.println((int)23.7);//23
System.out.println((int)-45.88f);//-45
注意点:
1.不能对布尔值进行转换
2.不能把对象类型转换为不相干的类型
3.在把高容量转换到低容量的时候,强制转换
4.转换的时候可能存在内存溢出,或者精度问题