Long ll = 102; // Error
Byte bb = 101; // No error
Why Long
assignment is resulting in compile time error while Byte
assignment is fine?
Long ll = 102
is resulting in compiler error "Type mismatch: cannot convert from int to Long". I assumed compiler will widen of 102 to long
and then box to Long
.
But it is not happening.
But Byte bb = 101;
is not generating compiler error. Here I guess, 101 is narrowed to byte
(being non-long integral constant) and then Boxed to Byte
.
When there is no problem with narrowing, what is the problem with widening?
This is happening because you are using Long
rather than long
. The Java autoboxing will not both convert from int
to long
and 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With