Difference between ‘==’ and ‘equals’ operator for comparison:

The comparison operator for objects may confuse some of the java novice programmers. In this article I am going to shed some thoughts on, when and where to use ‘equals’ and ‘==’ operators.

The ‘==’ operator is used to check if the two objects which are being compared are of the same object reference or not. This means to say that comparison is done on the memory location in which the objects are created / located. We use the ‘==’ operator to check whether the objects which we are being compared are the aliases or not. Object alias means, an object which is allocated on the memory and have different names to access the object location. For instance refer the sample code below:

String a = new String(“Bharath”);
 String b = new String(“Bharath”);
System.out.println(String ‘==’ operator output >—-> “ + (a == b)); // always results false, as the reference of object ‘a’ is different  from reference of object ‘b’
  

The ‘equals’ operator is used to compare the value / property contained in the comparing objects. For instance refer the sample code below:

  
String a = new String(“Bharath”);
 String b = new String(“Bharath”);
System.out.println(“String ‘equals’ operator output >—-> “ + a.equals(b));// results true because, the contents/property in both the objects ‘a’ and ‘b’ are the same.
 
example of object reference:


 

String a = new String(“Bharath”);
String b = new String(“Bharath”);
String c= b;
System.out.println(“comparison of ‘c’ and ‘b’ output >—-> “+(c==b)); //results true as object ‘c’ is reference of object ‘b’; in other words ‘c’ is an alias of ‘b’
System.out.println(“comparison of ‘c’ and ‘a’ output >—-> “+(c==a));//results false as object ‘c’ is not a reference of object ‘b’