Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

== operator on objects in Java

Tags:

java

casting

I am not able to understand the difference in the way obj and obj2 objects are created in the following code. In particular, I am not sure how a primitive is cast to an object. Looking at some of the other questions here, I thought this was not possible. But the following program compiles and runs fine. In the first case, the output is false and in the second case it is true.

public class Test {

    public static void main(String args[]){

        Integer num = new Integer(3) ;
        Object obj = num;
        Integer[] integerArr = {1, 2, 3, 4};
        Object[] objArr = integerArr;
        boolean contains = false;

        for (int i = 0; i < objArr.length; i++){
            if (objArr[i] == obj){
                contains = true;
                break;
            }
        }

        System.out.println(contains);

        int num2 = 3 ;
        Object obj2 = num2;
        Integer[] integerArr2 = {1, 2, 3, 4};
        Object[] objArr2 = integerArr2;
        boolean contains2 = false;

        for (int i = 0; i < objArr2.length; i++){
            if (objArr2[i] == obj2){
                contains2 = true;
                break;
            }
        }

        System.out.println(contains2);
    }

}
like image 584
B M Avatar asked Mar 06 '13 00:03

B M


1 Answers

The == operator between objects tests for identity (if two objects are exactly the same), whereas the equals() method tests for equality (whether two objects have the same value).

Most of the time, you'll be interested in equality. By chance, the example you provide in the question actually works, because Integer objects are cached (usually in the range -127 to 127, although this is configurable), but if you tested for identity using a bigger number, it's quite possible that the test will fail.

For example, this will evaluate to true:

Integer a = 127;
Integer b = 127;
a == b // true

Whereas this will evaluate to false!

Integer a = 128;
Integer b = 128;
a == b // false

Bottom line: play it safe and always use equals() for testing equality between objects.

like image 93
Óscar López Avatar answered Sep 24 '22 02:09

Óscar López