In Java programming language widen and boxing doesn't work, but how does it work in following example?
final short myshort = 10;
Integer iRef5 = myshort;
Why does this work? Is this not the same as widen and then box?
But if I write the following code:
final int myint = 10;
Long myLONG = myint;
why it doesn't work?
Widening − Converting a lower datatype to a higher datatype is known as widening. In this case the casting/conversion is done automatically therefore, it is known as implicit type casting. In this case both datatypes should be compatible with each other.
Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you.
Primitive int type can be auto-widened to big sized primitive types or can be auto-boxed to Integer wrapper class type but can not be converted into Double or Long wrapper class type.
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.
Following what others have said, I can confirm that I can compile your first example with the Eclipse compiler, but not the second. With the javac
compiler, both don't compile, as stated by Vlad
This seems to be a bug in either compiler! Let's consult the JLS to find out, which one is right :-)
With java 7 both the examples are not working. you will get below exception:
Type mismatch: cannot convert from short to Integer
Type mismatch: cannot convert from int to Long
Because the problem is not because of boxing but because of conversion.
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