Differences between == and equals() method in Java

DifferencesJavaObject Oriented Programming

In java both == and equals() method is used to check the equality of two variables or objects.== is a relational operator which checks if the values of two operands are equal or not, if yes then condition becomes true. equals() is a method available in Object class and is used to compare objects for equality. In order to compare custom objects, we must override the default implementation of the equals method in the custom class. In this article, we'll cover the various differences between == and equals method using relevant examples.

Differences

Following are the important differences between == and equals() method.

Sr. No. Key == equals() method
1 Type == is an operator. equals() is a method of Object class.
2 Comparision == should be used during reference comparison. == checks if both references points to same location or not. equals() method should be used for content comparison. equals() method evaluates the content to check the equality.
3 Object == operator can not be overriden. equals() method if not present and Object.equals() method is utilized, otherwise it can be overridden.

Example

In this example, we've checked string objects and other primitives using == and using equals method. As == compares the references and will return false and equals() method compares the content thus it will return true as shown below −

JavaTester.java

public class JavaTester { public static void main(String args[]) { String s1 = new String("TUTORIALSPOINT"); String s2 = new String("TUTORIALSPOINT"); //Reference comparison System.out.println(s1 == s2); //Content comparison System.out.println(s1.equals(s2)); // integer-type System.out.println(10 == 10); // char-type System.out.println('a' == 'a'); } }

Output

false
true
true
true

Example

In this example, we've checked two custom objects using == and using equals method. As == compares the references and will return false and equals() method compares the content thus it will return true as shown below −

JavaTester.java

public class JavaTester { public static void main(String args[]) { Student s1 = new Student(); s1.id = 1; s1.name = "Sam"; Student s2 = new Student(); s2.id = 1; s2.name = "Sam"; System.out.println("s1 == s2 : " + (s1 == s2)); System.out.println("s1.equals(s2) : " + s1.equals(s2)); } } class Student { public int id; public String name; @Override public boolean equals(Object obj) { Student s = (Student)obj; return this.id == s.id && this.name.equals(s.name); } }

Output

s1 == s2 : false
s1.equals(s2) : true
raja
Updated on 19-Aug-2022 13:00:31

Advertisements