Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using == for a primitive and a boxed value, is autoboxing done, or is unboxing done

The following code compiles (with Java 8):

Integer i1 = 1000; int i2 = 1000; boolean compared = (i1 == i2); 

But what does it do?

Unbox i1:

boolean compared = (i1.intvalue() == i2); 

or box i2:

boolean compared = (i1 == new Integer(i2)); 

So does it compare two Integer objects (by reference) or two int variables by value?

Note that for some numbers the reference comparison will yield the correct result because the Integer class maintains an internal cache of values between -128 to 127 (see also the comment by TheLostMind). This is why I used 1000 in my example and why I specifically ask about the unboxing/boxing and not about the result of the comparison.

like image 811
Thirler Avatar asked May 26 '15 09:05

Thirler


People also ask

What is Autoboxing and unboxing of primitive types?

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.

Is Autoboxing and boxing same?

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

Which version of JDK is Autoboxing and unboxing introduced?

Java introduced the concept of Autoboxing and Unboxing since Java 5. Using this concept we can interchangeably convert the primitive data types into their respective wrapper classes. Let's start discussing what is autoboxing and unboxing in Java.

Who is responsible for performing Autoboxing and unboxing in Java?

Who is responsible for performing Autoboxing and unboxing in java? Java compiler is responsible for making such conversions. Before java 5 we used to write such code for performing Autoboxing.


1 Answers

It is defined in the JLS #15.21.1:

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

And JLS #5.6.2:

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

  • If any operand is of a reference type, it is subjected to unboxing conversion [...]

So to answer your question, the Integer is unboxed into an int.

like image 74
assylias Avatar answered Oct 19 '22 04:10

assylias