1

what is the difference?

public static void main(String[] args){
            Integer integer1=1000;
            Integer integer2=1000;
            System.out.println(integer1==integer2);
        }

Result:false

public static void main(String[] args){
        Integer integer1=100;
        Integer integer2=100;
        System.out.println(integer1==integer2);
    }

Result:true

We can Try it!

5 Answers5

2

All integers between -128 and 127 are cached, because they are used more often. If you want the first example to work, try:

    public static void main(String[] args){
        Integer integer1=1000;
        Integer integer2=1000;
        System.out.println(integer1.equals(integer2));
    }

Or, use an int instead of an Integer, as an Integer is an object.

tckmn
  • 57,719
  • 27
  • 114
  • 156
2

As per JLS 5.1.7:

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Integer between -128 to 127 are pooled in Java . Look at this source code :

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

Integer between -128 to 127 are pooled in java.

Below results in autoboxing and 2 different objects are created:

Integer integer1=1000;integer1 and integer2 are referring to 2 different objects
Integer integer2=1000;

Integer integer1=100;both refer to the same because of pooling
Integer integer2=100;
ajay.patel
  • 1,957
  • 12
  • 15
  • No, you can't be sure that `Integer i1 = 1000;` and `Integer i2 = 1000;` refer to different objects. – jarnbjo Jul 08 '13 at 13:42
1

You have Integer as a reference type. == only compares references when used with objects.

Due to immutability, and interning/pooling, small values of an Integer(within the range [-128, 127] at a minimum, though this is implementation specific and should not be relied upon) may be set to reference the same object.

For the first example, the large numbers forgo interning, ergo different references, and it evaluates to false.

In the second, the Integers are the same reference, and the comparison is true.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
0

You can simply use int instead of Integer and it will work. Otherwise refer to any other answer about == vs equals().

Brinnis
  • 906
  • 5
  • 12