Java Primitive conversions in assignment context Long and int

前端 未结 3 2002
春和景丽
春和景丽 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:35

    This is happening because you are using Long rather than long. The Java autoboxing will not both convert from int to longand then autobox long to Long in the same step.

    Change your code to long ll and it will work.

    There is no marker in java for byte primitives - any value entered within a valid range for a byte (-128 to +127) can be treated as either a byte or an integer depending on context. In this case it processes it as byte and then autoboxing is able to work on it.

    I'm not sure why the decision was made to have Java work this way. It does seem that byte handling is inconsistent from all the other number types.

提交回复
热议问题