Sunday, April 5, 2009

Puzzle 12 – Solution

The key here is that ‘Integer objects are cached. 256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array’

You use auto-boxing, when you say,
Integer first = 100;

This is automatically translated by the Java compiler to the following:

Integer first = Integer.valueOf(100);

So, when you use autoboxing, you are really implicitly calling the method Integer.valueOf(int i).

Now, the method Integer.valueOf(int i) contains an optimization. It has a cache containing Integer objects for all the values between -128 and 127. If you call the method with an int that is in this range, then the method does not create a new Integer object; instead, it returns one of the existing Integer objects in the cache. Creating a new object is relatively expensive, so using a cache like this makes programs run more efficiently.

That means that if you do something like this:

Integer first = 100;
Integer second = 100;
You are calling Integer.valueOf(int i) two times, with the same value 100, which is in the cache - so the method will return the same Integer object from the cache for both first and second.

Since ==, when used on objects, checks if the two expressions on both sides of the == are the same object, the comparison first == second will return true.

Note that for numbers not in the range -128 to 127, Integer.valueOf(int i) will return a new Integer object.

The solution to this problem is based on an original post by Jesper Young at Java-Ranch.

Sorry no correct answers this week!

No comments:

Post a Comment

Solution for this question?