public class AutoConvertDetail{
public static void main(String[] args){
//细节1: 有多种数据类型混合运算时,
//系统自动将所有数据转换成容量最大的那种数据类型,然后再进行计算
int n1 10;
//float d1 = n1+1.1; //❌ n1+1.1=>结果类型是double,精度大,而float小,
//从double转化为float会有损失,不兼容。
//double d1 = n1 + 1.1;//√
float d1 = n1+1.1F;//√ 指出1.1是float类型
/*细节2:所以当我们把精度(容量)大数据类型赋值给精度(容量)小的数据类型时,
就会报错,反之就会进行自动类型转换。*/
//细节3:编译器规定(byte,short)和 char之间不会相互转换
/*当把一个具体数赋给byte时,先判断该数是否在byte的范围内,如果是就可以
当把变量赋值给byte时,会直接上类型的判断。*/
byte b1 = 10;//√, -128——127
//int n2 = 1;//n2是int
//byte b2 = n2;//×
//char c1 = b1;//× byte不能自动转成char
//细节4:byte,short,char 三者间可以进行计算,不管是单种类型还是混合在计算时首先转换为int类型
byte b2 = 1;
byte b3 = 2;
short s1 = 1;
//short s2 = b2 + s1;//b2+s1 =>int,int转换到short可能会有精度损失
int s2 = b2 + s1;
//byte b4 = b2+ b3;//× b2+b3 => int
//细节5:布尔类型boolean 不参与转换
boolean pass = true;
//int number100 = pass;//× boolean不参与类型的自动转换
//细节6:自动提升原则:表达式结果的类型自动提升为操作数中最大的类型
}
}
自动类型转换细节6点
最新推荐文章于 2024-06-04 22:50:27 发布