Java widening conversions

后端 未结 5 977
时光取名叫无心
时光取名叫无心 2020-12-28 14:55

I\'m preparing for Java 7 certification and have the following question.

Byte b = 10 compiles ok. Looks like the compiler is narrowing int 10 to byte 10

5条回答
  •  生来不讨喜
    2020-12-28 15:40

    The basic rules are:

    • you can't convert-and-autobox in one step (JLS 5.1.7 defines the boxing conversions, and it doesn't include convert-and-autobox type conversions, so they're not allowed)
    • you can't implicitly narrow a type

    These rules explain why Long l = 10 doesn't work, as well as new Byte(10). The first would require the int literal 10 to be widened to a long and then be boxed, which isn't allowed. (More precisely, it would require a conversion from int to Long, which JLS 5.1.7 doesn't define.) The second would require the int literal 10 to be implicitly narrowed to a byte, which isn't allowed.

    But there are exceptions to the rule. Byte b = 10 is explicitly allowed by JLS 5.2:

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

    • A narrowing primitive conversion followed by a boxing conversion may be used if the type of the variable is:
      • Byte and the value of the constant expression is representable in the type byte.

    (some irrelevant parts omitted)

    Lastly, new Long(10) works because the int literal 10 can be automatically widened to a long 10L.

提交回复
热议问题