Difference between equals() and == in Java


Java object has a Memory Location and State (depends on the values in the object).

Integer intObj1 = new Integer(10);

Above we have created an object called "intObj1" and it has a memory location. And also we have assigned value 10 to it,

The “==” operator
Used to compare two Objects. Comparing means checking to see if the two objects are referring to the same memory location.
Example :

String str1 = new String("techoverloads");
// now str2 and str1 reference the same place in memory
String str2 = str1;
if(str1== str2)
   System.out.printlln("str1==str2is TRUE");
else
  System.out.println("str1==str2is FALSE");

Result is,

str1==str2 is TRUEThe equals() method
Used to compare contents of two objects.Checks only the values, not their locations in memory.
Example:

String obj1 = new String("xyz");
String obj2 = new String("xyz");
if(obj1.equals(obj2))
   System.out.printlln("obj1==obj2 is TRUE");
else
  System.out.println("obj1==obj2 is FALSE");

Result is,
obj1==obj2 is TRUE

The "equals()" method is defined in the object class and it's default behavior is as same as the "==" operator. But it is overridden in-order to compare only the contents of the object instead of the location. Java string class overrides the default implementation of "equals()" method and above is an example of that.

Comments