Converting from Java primitive to wrapper classes

前端 未结 3 2173
谎友^
谎友^ 2021-02-09 23:22

I am mystified by the behavior of the Java compiler when assigning primitives to wrapper class references. Please see the code below. The lines with comments don\'t compile.

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-10 00:08

    Let's look at the types of conversions allowed in an assignment context.

    Principally:

    Assignment contexts allow the use of one of the following:

    • an identity conversion

    • a widening primitive conversion

    • a widening reference conversion

    • a boxing conversion optionally followed by a widening reference conversion

    • an unboxing conversion optionally followed by a widening primitive conversion.

    (Note my emphasis on one.)

    Most of your examples that do not compile, for example

    Integer s11 = (short)7;
    

    require a widening primitive conversion followed by a boxing conversion. This is not a permitted conversion.

    But then you might wonder why the following example does compile:

    Byte s9 = (short)7;
    

    This is a narrowing primitive conversion followed by a boxing conversion.

    This is a special case:

    In addition, if the expression is a constant expression 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.

    • Short and the value of the constant expression is representable in the type short.

    • Character and the value of the constant expression is representable in the type char.

    This special case is necessary because there is no way to express an integer literal of a type narrower than int.

提交回复
热议问题