7.查漏补缺——byte/short/char


一、byte/short/char隐式强制类型转换

  • 对于byte/short/char三种类型来说,如果右侧赋值的数值没有超过范围,那么javac编译器将会自动隐含地为我们补上一个(byte)(short)(char)
  • 如果没有超过左侧变量范围,编译器补上强制类型转换
  • 如果右侧的数值超过左侧变量范围,那么编译器直接报错
public class Demo01Notice{
    public static void main(String[] args){
        // 右侧确实是一个int类型的数值,但是没有超过左侧的范围,就是正确的写法
        // int --> byte, 不是自动类型转换
        byte num1 = /*(byte)*/ 30;
        System.out.println(num1);
        
        // byte num2 = 128; // 右侧超过了左侧的范围
        
        // int --> char, 没有超过范围
        // 编译器将会自动补上一个隐含的(char)
        char zifu = /*(char)*/ 65;
        System.out.println(zifu); // A
    }
}

二、编译器的常量优化

在给变量进行赋值的时候,如果右侧的表达式当中全是常量,没有任何变量,那么编译器javac将会直接将若干个常量表达式计算得到结果。

short result = 5 + 8; // 等号右边全是常量,没有任何变量参与运算

编译之后,得到的.class字节码文件当中相当于【直接就是】:

short result = 13;

右侧的常量结果数值,没有超过左侧范围,所以正确。

这称为“编译器的常量优化”

但是注意,一旦表达式当中有变量参与,那么就不能进行这种优化了。

public class Demo02Notice{
    public static void main(String[] args){
        short num1 = 10; // 正确,没有超过范围
        
        short a = 5;
        short b = 8;
        // short + short --> int + int -->int
        //short result = a + b; // 错误写法,左侧需要int
        
        // 右侧不用变量,而且采用常量,而且只有两个常量,没有别人
        short result = 5 + 8;
        System.out.println(result);
        
        // short result2 = 5 + a + 8; // 18
    }
}

Author: Wolfwotz
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source Wolfwotz !
  TOC