Difference Between == and equals method in Java with Example : Core Java Interview Question

Since Strings are objects, the equals(Object) method will return true if two Strings have the same objects. The == operator will only be true if two String references point to the same underlying String object. Hence two Strings representing the same content will be equal when tested by the equals(Object) method, but will only by equal when tested with the == operator if they are actually the same object.


In other words ,

Example #1:

Integer i = new Integer(10);
Integer j = i;

in the above code. i == j is true because both i and j refer to the same object.
a
Example #2:

Integer i = new Integer(10);
Integer j = new Integer(10);

In the above code, i == j is false because, although they both have the value 10, they are two different objects.





About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry