In java both == and equals() method is used to check the equality of two variables or objects.
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. |
2 | Object | == operator can not be overriden. | equals() method if not present and Object.equals() method is utilized, otherwise it can be overridden. |
Example of == vs equals method
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