The code listed below shows a classic result related to boxing and unboxing in Java.
public static void main(String[] args) {
Integer i1 = 127;
Integer i2 = 128;
Integer i3 = 127;
Integer i4 = 128;
Integer i5 = new Integer(127);
Integer i6 = new Integer(127);
System.out.println(i1 == i3); // true
System.out.println(i2 == i4); // false
System.out.println(i5 == i6); // false
System.out.println("0000000000" == "0000000000"); // true
}
- Boxing is the conversion from primitive type to wrapper class, like from
int
toInteger
. - Unboxing is from wrapper class to primitive type.
==
compares the references of two objects. equals()
method compares the values of two objects. JVM will auto-box some primitives into the same wrapper class object. These objects will be saved in buffer in order to be used repeatly.
These primitives include:
- boolean
- byte
- short and int between -128 and 127
- char between 0 and
0x7f
In conclusion, for two objects with the same value,
- If one of them are primitive,
==
is always true. (unboxing wrapper) - If both are wrapper class object
- If one of them is created by
new
,==
is false. (allocates new space) - Else if
Boolean
,Byte
,Float
andDouble
,==
is true. - Else if
Short
,Integer
andLong
, and the value is between -128 and 127,==
is true - Else if
Character
with value between 0 and0x7f
,==
is true - Else,
==
is false
- If one of them is created by
It is worthy to note here if we want to compare values, we should always use equals()
method. I have made such mistake before..
Boxing and unboxing are automatically done in JVM. For example,
int i = 10;
Integer a = i; // boxing
int k = a; // unboxing
But we can still do it manually like
int i = 10;
Integer a = new Integer(i); // boxing
int j = a.intValue(); // unboxing
Let’s look at an example here.
Integer d = new Integer(10);
d++; // unboxing d first, then ++, finally boxing result
In method overload case, if we have following two methods in a class
public void test(double num);
public void test(Integer num);
For a int
k, if we do test(k)
, Java will call test(double num)
instead of the other one. Because in Java 4, we don’t have boxing and unboxing feature. The result is due to backwards compatibility.