Java - why does char get implicitly cast to byte (and short) primitive, when it shouldn't?

前端 未结 5 702
情歌与酒
情歌与酒 2020-12-03 18:39

Certain functionality of the compiler puzzles me (Oracle JDK 1.7 using Eclipse).

So I\'ve got this book that says char primitive needs to be explicitly cast to short

5条回答
  •  醉话见心
    2020-12-03 19:22

    Why does the following work as well?

    Because '&' is a constant expression whose value fits in byte.

    JLS 14.4.2

    If a declarator has an initialization expression, the expression is evaluated and its value is assigned to the variable.

    JLS 5.2

    Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable.

    ....

    In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

    • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

提交回复
热议问题