Java Primitive conversions in assignment context Long and int

前端 未结 3 1998
春和景丽
春和景丽 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条回答
  •  不思量自难忘°
    2021-02-07 05:18

    1. Auto boxing does not also cast; eg it will only auto box a long to a Long, an int to an Integer, etc.
    2. In Java numeric literals are inherently int

    So, it should be clear why the assignment to Long won't work: an int is trying to be cast to a long then auto boxed to a Long in one step... no go.

    However, numeric literals in the range -128 to 127 may be interpreted as byte literals in the right context, so that's why the assignment to Byte works.

提交回复
热议问题