Java中的两种转换方式:
1.低精度转高精度
(1)隐式转换(自动转换)
由低精度向高精度转换
byte —> short —> int —> long —> float —> double
char <—> int
注意:在char的取值范围内,两者是相互兼容的
举个栗子:
public static void main(String[] args) {
char e = 'a';
int b = e - 2;
System.out.println(b); //95
}
a的Unicode编码是97,所以97-2=95
(2)显式转换(强制转换)
2.高精度转低精度
显式转换(强制转换)
语法:(类型名)要转换的值
举个栗子:
public static void main(String[] args) {
int a = 25;
byte b = (byte)a;
System.out.println(b); //25
}
显示转换导致精度损失
举个栗子:
public static void main(String[] args) {
float f = (float)3.1415926; //数据失准
System.out.println(f); //3.1415925
}
public static void main(String[] args) {
float f = (float)3.1415926;
int i = (int)f;
System.out.println(i); //3 小数点丢失
}
public static void main(String[] args) {
byte b = (byte)129;
System.out.println(b); //-127 byte的取值范围是-127——128 数值越界溢出
}