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");
  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.

String obj1 = new String("xyz");
String obj2 = new String("xyz");
   System.out.printlln("obj1==obj2 is TRUE");
  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.


  1. It is necessary to know the difference between a cloth being soft versus being flexible. A material’s stiffness is its capacity to withstand bending beneath stress. A good example could be seen by evaluating an ABS ruler to a Nylon rule. Humidifiers for Bedroom Although ABS is a tougher material than Nylon, a Nylon ruler would be rather more difficult to bend than an ABS ruler.


Post a Comment