-2
public class MainClass

{

    public static void main(String[] args)
    {
        Integer i1 = 127;

        Integer i2 = 127;

        System.out.println(i1 == i2);

        Integer i3 = 128;

        Integer i4 = 128;

        System.out.println(i3 == i4);
    }
}

i1,i2,i3,i4 are not objects I guess they are only reference variables. So how they work differently from class variables?

Answer I heard is

true
false

But how? Why is it different for 127 and 128?

Renzo
  • 26,848
  • 5
  • 49
  • 61
Sahiba
  • 1
  • 1

2 Answers2

1

Since Java 5, wrapper class caching was introduced. The following is an examination of the cache created by an inner class, IntegerCache, located in the Integer cache. For example, the following code will create a cache:

Integer myNumber = 10

or

Integer myNumber = Integer.valueOf(10);

256 Integer objects are created in the range of -128 to 127 which are all stored in an Integer array. This caching functionality can be seen by looking at the inner class, IntegerCache, which is found in Integer:

So when creating an object using Integer.valueOf or directly assigning a value to an Integer within the range of -128 to 127 the same object will be returned. Therefore, consider the following example:

Integer i = 100;
Integer p = 100;
if (i == p)  
System.out.println("i and p are the same.");
if (i != p)
System.out.println("i and p are different.");   
if(i.equals(p))
System.out.println("i and p contain the same value.");

The output is:

i and p are the same.
i and p contain the same value.

It is important to note that object i and p only equate to true because they are the same object, the comparison is not based on the value, it is based on object equality. If Integer i and p are outside the range of -128 or 127 the cache is not used, therefore new objects are created. When doing a comparison for value always use the “.equals” method. It is also important to note that instantiating an Integer does not create this caching.

Remember that “==” is always used for object equality, it has not been overloaded for comparing unboxed values

Also see Integer wrapper objects share the same instances only within the value 127?

Community
  • 1
  • 1
Dave
  • 967
  • 10
  • 23
0

Integer is an object and hence the == check if the variables refer to the exact same instance. Equality of objects can be checked using the myObject.equals(otherObject)

int is the primitive type of Integer and in that case the == would return true if both the ints have the same value

update: please note that in some case, as for String for example, two variables can share the same reference depending from the code and the compiler but still it is not something you should base your code logic on.

Paizo
  • 3,986
  • 30
  • 45