java数据类型转换分为强制类型转换和自动类型转换
自动类型转换的规则有系统自动完成,从低级自动转向高级,规则如下:
byte->short(char)->int->long->float->double
例如:
public class Test {
public static void main(String[] args) {
byte b = 3;
short s = b;
System.out.println("s=" + s);
}
}
此处,byte类型的b会自动转换成short并赋值给s
但是,从高级转换为低级就不行,必须使用强制类型转换
如不使用强转,下述代码就会报错:
public class Test {
public static void main(String[] args) {
short s = 3;
byte b = s;
System.out.println("s=" + s);
}
}
正确的做法为:
public class Test {
public static void main(String[] args) {
short s = 3;
byte b = (byte) s;
System.out.println("s=" + s);
}
}