Java_005 数据类型转换

#表达式类型自动提升:
如一个byte型的变量在运算期间类型会自动提升为int型

public class example01 {
    
    
    public static void main(String[] args) {
    
    
        byte b1 = 3;
        byte b2 = 4;
        byte b3 = b1+b2;//不兼容的类型: 从int转换到byte可能会有损失
        System.out.println(b3);
    }
}

##解决方法:
必须将第五行的代码修改为

	byte b3 = (byte) (b1+b2)

tip:

  1. 表达式是指由变量和运算符组成的一个算式。
  2. 变量在表达式中进行运算时,也有可能发生自动类型转换,这就是表达式数据类型的自动提升。


#强制类型转换导致精度丢失

public class example02 {
    
    
    public static void main(String[] args) {
    
    
        byte a;
        int b = 298;
        a =(byte)b;
        System.out.println("b="+b);
        System.out.println("a="+a);
    }
}

##运行结果

	b=298
	a=42

猜你喜欢

转载自blog.csdn.net/weixin_49207937/article/details/114412067
今日推荐