Java编译器的优化

public class Notice {
    public static void main(String[] args) {
        // 右侧20是一个int类型,但没有超过左侧数值范围,就是正确的
        // int --> byte 不是自动类型转换
        byte num1 = 20;
        System.out.println(num1); // 20
        
        // 错误:不兼容的类型: 从int转换到byte可能会有损失
        // byte num2 = 128;
        // System.out.println(num2);
        
        char zifu = 65;
        System.out.println(zifu); // A
    }
}

对于byte/short/char三种数据类型,如果右侧没有超过左侧数值范围,则编译器会自动进行优化,在右侧隐含地添加(byte) / (short) / (char)

如果右侧超过左侧数值范围,则编译器直接报错。

public class Notice2{
    public static void main(String[] args){
        short num1 = 10, num2 = 8;
        // short + short --> int + int --> int
        // short = int + int
        // short num3 = num1 + num2; // 错误写法,左侧需要的是int类型
        // System.out.println(num3);
        
        // 右侧只有常量,没有变量参与运算
        short num4 = 10 + 8;
        System.out.println(num4); // 18
    }
}

在给变量赋值时,如果右侧表达式中只有常量,没有变量,那么编译器javac会直接计算出右侧的值,然后赋值给左侧,编译后的.class文件里直接就是 short num4 = 18

这称为“编译器的常量优化”,但是一旦表达式中有变量,则不能进行这种优化。

原文地址:https://www.cnblogs.com/roadlandscape/p/12045837.html