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

前端 未结 5 700
情歌与酒
情歌与酒 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:09

    This is called compile-time narrowing of constants. It is described in section 5.2 of the Java Language Specification:

    The compile-time narrowing of constants means that code such as:

    byte theAnswer = 42;
    

    is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required.

    Same goes for character literals: if its value fits in a byte, no conversion is required; if the value does not fit, you must put in a cast, or you would get a compile error.

    For example, this would not compile:

    byte bc = '\uff12'; // Does not compile without a cast
    

    but this compiles fine:

    byte bc = (byte)'\uff12';
    

提交回复
热议问题