Comparing Integer objects [duplicate]

I have the following code:

public class Test {

    public static void main(String[] args) {

        Integer alpha = new Integer(1);
        Integer foo = new Integer(1);

        if(alpha == foo) {
            System.out.println("1. true");
        }

        if(alpha.equals(foo)) {
            System.out.println("2. true");
        }

    } 

}

The output is as follows:

2. true

However changing the type of an Integer object to int will produce a different output, for example:

public class Test {

    public static void main(String[] args) {

        Integer alpha = new Integer(1);
        int foo = 1;

        if(alpha == foo) {
            System.out.println("1. true");
        }

        if(alpha.equals(foo)) {
            System.out.println("2. true");
        }

    } 

}

The new output:

1. true
2. true

How can this be so? Why doesn't the first example code output 1. true?


Solution 1:

For reference types, == checks whether the references are equal, i.e. whether they point to the same object.

For primitive types, == checks whether the values are equal.

java.lang.Integer is a reference type. int is a primitive type.

Edit: If one operand is of primitive type, and the other of a reference type that unboxes to a suitable primitive type, == will compare values, not references.

Solution 2:

Integer objects are objects. This sounds logical, but is the answer to the question. Objects are made in Java using the new keyword, and then stored in the memory. When comparing, you compare the memory locations of the objects, not the value/properties of the objects.

Using the .equals() method, you actually compare the values/properties of objects, not their location in memory:

new Integer(1) == new Integer(1) returns false, while new Integer(1).equals(new Integer(1)) returns true.


ints are a primitive type of java. When you create an int, all that is referenced is the value. When you compare any primitive type in Java, all that is compared is the value, not the memory location. That is why 5 == 5 always returns true.

When you compare an Integer object to a primitive type, the object is cast to the primitive type, if possible. With an Integer and an int this is possible, so they are compared. That is why Integer(1).equals(1) returns true.