Java Primitive conversions in assignment context Long and int

前端 未结 3 2036
春和景丽
春和景丽 2021-02-07 04:56
Long ll = 102; // Error
Byte bb = 101; // No error

Why Long assignment is resulting in compile time error while Byte assignme

3条回答
  •  萌比男神i
    2021-02-07 05:32

    See 5.1.7 Boxing Conversion of the JLS

    • If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p

    Because 102 is an integer literal, it's type is int and auto boxing will convert it to Integer (as the spec says), but an Integer can not be casted to Long.

    Thus when you use a long literal or cast the int literal to long the JLS will use the boxing conversion and the result will be a Long object.

    This will be fine

    Long long1 = (long) 102;
    Long long2 = 102L;
    Long long3 = 102l;
    

    The second one

    Byte bb = 101;
    

    works, because of the 5.2. Assignment Conversion

    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.

    So 101 is a integer literal, but there is an assignment that needs a narrowing conversion (int -> byte) and the value of the int is within the byte value range. Thus it is representable as the variable type (see spec) and it is converted.

    This will NOT WORK of course

     Byte bb = 128; // can not be represented as the variable type. Thus no narrowing conversion.
    

提交回复
热议问题