Integer a = 5;
int b = 5;
System.out.println(a==b); // Print true
But why does this print true, since a is an instance of an Integer
and b is a primitive int
?
Integer a = 5;
int b = 5;
System.out.println(a==b); // Print true
But why does this print true, since a is an instance of an Integer
and b is a primitive int
?
Java uses the concept of Unboxing
when you compare primitive and wrapper class. Where in a Integer
variable is translated into primitive int
type.
Following is what is happening with your code:
Integer a = 5; //a of type Integer i.e. wrapper class
int b = 5; //b of primitive int type
System.out.println(a==b) // a is unboxed to int type and compared with b, hence true
For more on Autoboxing
(reverse of Unboxing) and Unboxing
this link.
The correct answer is due to unboxing, but let's be more explicit here.
The rules for numerical equivalence are described in the Java Language Specification, specifically these rules:
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).
Since Integer
is convertible to a numeric type (per these rules), the values you're comparing become semantically equivalent to a.intValue() == b
.
It should be stressed that this conversion will fail if a
is null
; that is, you will get a NullPointerException
when attempting to do that equivalence check.
Beginning with JDK 5, Java added two important features: autoboxing and auto-unboxing.
Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent type wrapper whenever an object of that type is needed. There is no need to explicitly construct an object.
Auto-unboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a type wrapper when its value is needed.
With autoboxing, it is no longer necessary to manually construct an object in order to wrap a primitive type:
Integer someInt = 100; // autobox the int (i.e. 100) into an Integer
To unbox an object, simply assign that object reference to a primitive-type variable:
int unboxed = someInt // auto-unbox Integer instance to an int
Here all the post answer are correct.
Here your code at Compile time
public class Compare {
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer a=5;
int b=5;
System.out.println(a==b);
//the compiler converts the code to the following at runtime:
//So that you get it at run time
System.out.println(a==Integer.valueOf(b));
}
}