3

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?

Mandroid
  • 6,200
  • 12
  • 64
  • 134
  • 3
    The `new` keyword _always_ constructs a _new_ object. To make use of the cache you either have to rely on auto-boxing or manually use `Integer#valueOf(int)`. – Slaw May 24 '20 at 04:04

2 Answers2

5

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.

Mukesh Keshu
  • 467
  • 2
  • 13
  • 1
    *"Also note that the integer pool contains only integers from -128 to 127."* - By default. There is an obscure JVM command line option that can change the default: https://stackoverflow.com/a/30220901/139985 – Stephen C May 24 '20 at 04:27
  • @StephenC Thank you for that info. Edited my answer. – Mukesh Keshu May 24 '20 at 04:34
0

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.

Keet Sugathadasa
  • 11,595
  • 6
  • 65
  • 80