Caching of boxed values in Java

Viewed 266

I have following code:

Integer first = new Integer(4);
Integer second = new Integer(4);
System.out.println(first == second);
Integer third = 4;
System.out.println(first == third);
System.out.println(second == third);

As 4 falls between -128 to 127, I expect that Integer object wrapping 4 is cached once its created first time, and then its returned for other boxing statements, and so '==' check must return true. But its always false for above three cases.

Why is it so?

2 Answers

Because these assignments are made using the 'new' keyword, they are new instances created, and not picked up from the pool. Also note that the integer pool contains only integers from -128 to 127. For higher values, pool do not come to play.

Integer third = 4;
Integer fourth = 4;
Integer fifth = 130;
Integer sixth = 130;
Integer seventh = 127;
Integer eighth = 127;
System.out.println(third == fourth); // 4==4 Return true
System.out.println(fifth == sixth); // 130==130 Returns false
System.out.println(seventh == eighth); // 127==127 Returns true

edit As rightly mentioned in the comment, from Java 1.6 auto box limit can be extended by using -XX:AutoBoxCacheMax=new_limit from command line.

For reference types (Integer), use equals to compare the values of two Integers and == to compare whether the references point to the same object (i.e., share the same address). In most cases, it's equals what you want and not ==.

For primitive types (int), you have to use ==, and it compares the values to two ints. (equals doesn't work because it's defined on objects only, which primitives are not by definition.)

In your question, you are using the new Integer(3) keywors, which creates a new object in the pool. Hence, object references are not the same.

See this link for more information.

Related