Problem of comparing wrapper objects with == operator

One of my friend asked me to explain the caching of Integer object in the previous post. So I thought about elaborating it in detail. The examples in this article uses autoboxing so that we can think in that context to understand the issue of caching of objects in the previous post.

Comparing Integer objects with == operator

Well! we can write a program which “autoboxes” two int values into their Integer objects and compare them with == operator. The program is written below.

If you execute this program the output will be a and b are not equal. It is because we are not comparing two int values but two Integer values in the method “compare”. Both a and b are autoboxed to their wrapper classes when passed to method “compare”. And in the comparison statement if (a == b) we are not comparing int values but Integer objects; and comparison of wrapper objects with == operator is not based on their actual values but on their memory references. So when the statement if (a == b) executes the memory references of both a and b are compared and not actual values a and b holds. And as a result the program prints a and b are not equal.

Now we can run another program.

If you run the above program you can see the output as a and b are equal. The only difference the two program have is in the values a and b holds. Earlier it was “1000” and now it is “100”.

As we compared objects with == we can assure that in the second program the memory location of a and b are same; and so we can conclude that jvm “caches” the memory location when creating wrapper object like Integeror Long for some set of values. And the cached value ranges from “-128” to “+127”. You can change the values of both a and b and see the output.

So as we can see the == operator can result in different output when compares two Integer objects based on their values and that is the reason it is advised to use the .equals() method when comparing two Integer or Long objects.

So that is the problem of using == operator when comparing two objects.

Leave a Comment

Your email address will not be published. Required fields are marked *