在不同数据类型之间进行转换时,一般大容量(高精度)向小容量(低精度)转换时,都需要强制数据类型转换不然会编译报错;
小容量(低精度)向大容量(高精度)转换时, 可以自动数据类型转换
特殊规则: 如果整数在没有超出byte、short、char 的取值范围时,可以直接将整数的值赋值给byte、short、char 而不需要强制数据类型转换
public class MyTest {
public static void main(String[] args) {
short x = 10;
char y = 20;
// 出错,因为在编译阶段只是知道 x + y 的值是int类型,不进行运算,int 类型不能直接赋值给byte类型
// 我觉的应该是编译器不能确定运算后的值是否还在byte类型的范围内,因为编译器只进行语法检测不进行运算
byte n = x + y;
// 正确,将 x + y int类型的值先 强转成byte
byte m = (byte) (x + y);
// 正确
byte k = 30;
}
}
基本数据类型之间的运算
public class MyTest {
public static void main(String[] args) {
// 错,超出byte数据的范围
byte a = 1000;
long b = 10;
//错,编译器不进行运算,只是知道b/3是long类型的数据,long类型——>int类型 精度丢失
int e = b/3;
//错。丢失精度
int c = b;
//对,int / int ——>int 数据
int d = 10/3; //d = 3
//错,long->int->byte / int ——>int 类型;丢失精度
//而且 (byte、short、char 之间计算都会先转换成int类型的数据,再计算)
byte f = (byte)(int)b/3;
//错,编译器不进行运算,只是知道(byte)b/3结果是int类型
byte g = (byte)b/3;
int num = 10;
byte h = num/3;
//但是 这样就正确 (直接写值可以,但写的值所得结果超出byte范围会编译出错)
byte i = 100/3; //(个人认为使用字面值时可以得出结果判断是否编译出错,使用变量时不进行计算)
//错,超出 byte 范围
byte k = 1000/3
byte x = 10;
short y = 20;
//出错,编译器不进行运算,只是知道x + y结果是int类型,int->short 精度丢失
short m = x + y;
char z = 'a';
//正确 ,(byte、short、char 之间计算都会先转换成int类型的数据,再计算)
int n = z + 100; //197
}
}