equals() VS ==

Table of contents

equals() is a method that compares the actual content of the object.
"==" is an operator that compares the memory or reference location of an object in the heap.
equals()
The String equals() function compares two strings based on their data/content. It is defined in java.lang package.
It returns true if all of the contents of both strings match. It returns false if none of the characters match.
public class Hello {
public static void main(String []args) {
String s1 = "Welcome";
String s2 = "Welcome";
String s3 = new String ("welcome");
System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
}
}
Output:
true
false
"==" operator
"==" checks if both objects point to the same memory location.
Just like equals() method, "==" also returns a boolean output. Since "==" is an operator, it is not overrideable, and hence we avoid using it for comparing two objects.
class Hello {
public static void main(String[] args)
{
System.out.println(10 == 20); //int type
System.out.println('a' == 'b'); //char type
System.out.println('a' == 97.0); //char and double type
System.out.println(true == true); //bool type
}
}
Output:
false
false
true
true
Key difference between equals() and ==
"==" Operator | equals() Method |
"==" is an operator in Java and hence it can't be overridden. | equals() is a method in Java and hence it can be overridden. |
majorly used to compare the reference values and objects. | used to compare the actual content of the object. |
takes O(1) time for comparison. | takes O(1) time for normal objects and O(n) time for String objects. |
"==" operator cannot be overridden. | equals() method and can be overridden. |
throws compile time error if the two variables are not of the same data type. | returns a "false" value if the objects are not of the same type. |
Subscribe to my newsletter
Read articles from Parvathi Somasundaram directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
