This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Boxing, ==, equals(). Total confusion

Jia Ramharai
Greenhorn
Posts: 5
Hello All,
I am a bit confused about the 2 below code snippets:
Integer i1 = 1000;
Integer i2 = 1000;
if (i1 != i2) {
System.out.println("different objects");
}
if (i1.equals(i2)) {
System.out.println("meaningfully equal");
}

OUTPUT: different objects
meaningfully equal

Integer i3 = 10;
Integer i4 = 10;
if (i3 == i4) {
System.out.println("same objects");
}
if (i3.equals(i4)) {
System.out.println("meaningfully equal");
}

OUTPUT: same objects
meaningfully equal

I want to know how can this be possible? Both should use the same logic. Two wrapper objects can't be different and same at the same time.

Himai Minh
Ranch Hand
Posts: 1342
7
Yes. This is confusing.
For all Integer with values < 128 , those Integer instances work just like primitive. So, all those values can be compare by the == sign.
But all Integer with values >=128, they are treated as object. If the references refer to the same object, then " i1==i2" is true; otherwise, false.
Of course , when their values are the same, using .equal methods will return true.

For more detail, please refer to autoboxing in KB's book.

Mala Gupta
Author
Ranch Hand
Posts: 359
10
Jia,

Class Integer defines a nested static class - IntegerCache. By default, it creates an array of Integer objects with values -128 to 127. If you try to create an object of class Integer within this range, your object reference refers to the existing Integer object. In this case, class Integer doesn't creates a new object. This is the reason why the object references refer to the same Integer object for values -128 to 127, and return true when compared for equality using the operator ==.

For your reference, here's the code of class IntegerCache defined within class Integer:

With respect,
Mala

Mansukhdeep Thind
Ranch Hand
Posts: 1158
Welcome to the Ranch Jia. Please use the code button to post code snippets while asking questions. It makes the code much more legible.

Niraj Jha
Ranch Hand
Posts: 63
For more detail :
Check JLS Specification

Dan Drillich
Ranch Hand
Posts: 1183
== and != in Integer literals adds a bit more to the subject...

Regards,
Dan

Jia Ramharai
Greenhorn
Posts: 5
Ok, if I understand well,
when the Integer is between -128 and 127 then the result is true for i1 == i2 but
when the Integer is outside of the range above, then the result is false for i1 == i2 because here there are two Integer objects that have been created.

Thank you all for your replies. :-)

Rachel Glenn
Ranch Hand
Posts: 95
yes, very confusing! I certainly hope this is not on the exam!