ashwin bhawsar wrote:I was going through the Auto-boxing topic of Kathy Sierra SCJP 6 (page 246). It says that if we try to compare 2 instances of wrapped objects, the objects are unwrapped and their values are compared.
That's wrong. The book says : When == is used to compare a primitive to a wrapper, the wrapper will be unwrapped and the comparison will be primitive to primitive.
I have compiled some rules the comparison of wrapper objects:
Integer i1 = 1000; //this is boxing
Integer i2 = 1000; //this is boxing
Integer i3 = 10; //this is boxing
Integer i4 = 10; //this is boxing
Integer i5 = new Integer(10); // this is not boxing
Integer i6 = new Integer(10); // this is not boxing
Compare Using Compare With Result
i1 == i2 false
i3 == i4 true
i5 == i6 false
i1 .equals() i2 true
i3 .equals() i4 true
i5 .equals() i6 true
Compare row 1,2 and 3 it looks confusing at first sight, as it was for me.
If you create a Wrapper object using boxing then its constructor will not be called, but valueOf() method will be called.
If you check the javadocs for this method, it says that this method caches frequently requested values.
Generally caching is done for:
1. Short and Integer from -128 to 127
2. Character from \u0000 to \u007f
So if you have Integer in this range then you won't get two different objects when you write Integer i3=10; Integer i4=10;. Therefore i3==i4 is true and i1==i2 false.
Please SearchFirst. This question has been asked many, many times before.
Piyush is right about the caching and the ranges, but with two additions:
1) Long also has the cache for values from -128 to 127.
2) the upper bound for Integer can be increased using a specific system property (which I can't remember right now).