Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Widening and boxing with Java

Tags:

java

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?

like image 737
Mahesh Gurav Avatar asked Dec 22 '11 08:12

Mahesh Gurav


People also ask

What is widening in Java?

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.

Is Boxing and Autoboxing same in Java?

Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you.

Is primitive type can be widened to a wrapper class?

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.

What is Boxing in Java?

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.


2 Answers

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 :-)

like image 138
Lukas Eder Avatar answered Sep 30 '22 12:09

Lukas Eder


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.

like image 38
Sumit Singh Avatar answered Sep 30 '22 10:09

Sumit Singh