Both equals() and ‘==’ is used to check the equality of the objects but there is a significant amount of difference between equals() and ‘==’. The equals method is present in the java.lang.Object class and it is used to check the equivalence of the object (i.,e) to check if the content is equal whereas ‘==’ is used to check if the actual object instances are same or not.
== Operator
The ‘==’ operator is used to check if both the objects refers to the same place in the memory. Lets see that in the below example
String str1 = new String("javainterviewpoint"); String str2 = new String("javainterviewpoint"); if(str1 == str2) { System.out.println("Both Objects are equal"); } else { System.out.println("Both Objects are not equal"); }
If you have guessed “Both Objects are equal” then you are wrong, because ‘==’ checks for the memory here str1 and str2 are present in a different memory addresses, say str1 is at the address 0x12345 and str2 is at the address 0x23456 that is the reason we are getting “Both Objects are not equal” though the contents are same.
String str1 = new String("javainterviewpoint"); String str2 = str1; if(str1 == str2) { System.out.println("Both Objects are equal"); } else { System.out.println("Both Objects are not equal"); }
whereas the above code will give you the expected output “Both Objects are equal” as both object refers to the same place in the memory.
equals () method
The equals method checks for the content of both the str objects, we will get “Both Objects are equal” even when we compare the first example with equals() itself.
String str1 = new String("javainterviewpoint"); String str2 = new String("javainterviewpoint"); if(str1.equals(str2)) { System.out.println("Both Objects are equal"); } else { System.out.println("Both Objects are not equal"); }
The String class overrides the equals method to compare if the character in the String is equal. Thus we get the output as true as both holds the same string “javainterviewpoint”.
Leave a Reply