Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Primitive conversions in assignment context Long and int

Tags:

java

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?

like image 772
Lalith Avatar asked Dec 17 '13 10:12

Lalith


1 Answers

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.

like image 101
Tim B Avatar answered Oct 01 '22 14:10

Tim B