Puzzle 24: A Big Delight in Every Byte

Mixed-type运算最好不要搞的

下面这段代码运行后,会在控制台输出什么?

        for (byte b = Byte.MIN_VALUE; b < Byte.MAX_VALUE; b++) {
            if (b == 0x90) {
                System.out.print("Joy!");
            }
        }

答案是:空白。

原因很简单:0x90 = 144 > 127 = Byte.MAX_VALUE

当程序执行到 if (b == 0x90) 这里时,按照 JLS 15.21.1,If the promoted type of the operands is int or long, then an integer equality test is performed,所以这里进行的实际上是把 b 转成 int 型后再进行比较,鉴于 b 能赋予的最大值 Byte.MAX_VALUE 都比0x90小,0x90在 Byte 能表示的数值范围之外,这个循环执行结束都不会有 b == 0x90成立的。

有没有办法让 Joy! 输出呢?有,把0x90 cast 成 byte 就 OK 了:if (b == 0x90) 改成 if (b == (byte)0x90)

不同型的数参与同一个运算,确实很 confusing,很麻烦的。书中云,一般要避免这么做。

  1. Puzzle 5: The Joy of Hex 避免mixed-type运算。
  2. Puzzle 27: Shifty i's
  3. JLS 15.21.1 Numerical Equality Operators == and !=