Skip to content
欢迎扫码关注公众号

Java 解惑 -06:多重转型

问题

观察如下代码,你认为将打印什么? -1 吗?

java
System.out.println((int) (char) (byte) -1);

说明

上述代码实际上执行了四次类型转换,具体转换步骤如下:

  1. -1int 型 32 位;
    此时值为:ffffffff
  2. 转化为 byte 型是 8 位,此时执行了一个 窄化原生类型转换,直接将低 8 位之外的所有位全部砍掉;
    此时值为:ff
  3. 之后 byte 型转换为 char 型,执行的不是一个 拓宽原生类型转换,而是一个 拓宽并窄化原生类型转换byte 型首先被转换为 int 型,之后再转换为 char 型;
    • 拓宽并窄化原生类型转换的简单规则
      • 如果最初的数值类型是有符号的,那么就执行符号扩展;
      • 如果它是 char ,那么不管它将要被转换成什么类型,都执行零扩展。
    • 由于 byte 是有符号数,执行符号扩展,结果为:ffff
  4. charint 执行的是一个 拓宽原生类型转换
    char 转换到 int 执行的是零扩展,所以最终结果为:0000ffff ,打印出来是 65535

教训

教训

如果你通过观察不能确定程序将要做什么,那么它做的就很有可能不是你想要的。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.