java的基本数据类型自动转换
本文主要内容阐明java的自动数据类型转换
首先明确,数据总是由精度低到精度高方向转换
public class AutoConvert {
public static void main(String[] args) {
int n1 = 1;
byte n2 = n1;
}
}
由上图代码所示,编译报错,int类型变量不能由byte变量存储,int是4字节,byte是2字节
正确写法如下:
public class AutoConvert {
public static void main(String[] args) {
byte n1 = 1;
int n2 = n1;
}
}
下面,说明自动转换的规则:
char(2)--->int(4)--->long(8)--->float(4)--->double(8)
byte(1)---->short(2)--->int(4)---->long(8)--->double(8)
但是(byte,short)和char不能相互转换
byte不能转换char:

short不能转换char:

注意,在byte,short,char三者运算时,结果自动提升精度至int



浙公网安备 33010602011771号