1In general both equals() and == operator in Java are used to compare
2objects to check equality but here are some of the differences between the two:
3
41) .equals() and == is that one is a method and other is operator.
52) We can use == operator for reference comparison (address comparison)
6and .equals() method for content comparison.
7 -> == checks if both objects point to the same memory location
8 -> .equals() evaluates to the comparison of values in the objects.
93) If a class does not override the equals method, then by default it
10uses equals(Object o) method of the closest parent class
11that has overridden this method.
12
13// Java program to understand
14// the concept of == operator
15public class Test {
16 public static void main(String[] args)
17 {
18 String s1 = new String("HELLO");
19 String s2 = new String("HELLO");
20 System.out.println(s1 == s2);
21 System.out.println(s1.equals(s2));
22 }
23}
24Output:
25false
26true
27
28Explanation: Here we are creating two (String) objects namely s1 and s2.
29Both s1 and s2 refers to different objects.
30 -> When we use == operator for s1 and s2 comparison then the result is false
31 as both have different addresses in memory.
32 -> Using equals, the result is true because its only comparing the
33 values given in s1 and s2.
1// == operator
2String str1 = new String("Hello");
3String str2 = new String("Hello");
4System.out.println(str1 == str2); // output : false
5
6
7// equals method
8String str1 = new String("Hello");
9String str2 = new String("Hello");
10System.out.println(str1.equals(str2)); // output : true
1// Java program to understand
2// the concept of == operator and .equals() method
3public class Test {
4 public static void main(String[] args)
5 {
6 String s1 = new String("HELLO");
7 String s2 = new String("HELLO");
8 System.out.println(s1 == s2);
9 System.out.println(s1.equals(s2));
10 }
11}
12
13Output:
14false
15true
16
17Explanation:
18We can use == operators for reference comparison (address comparison) and
19.equals() method for content comparison. In simple words, == checks if both
20objects point to the same memory location whereas .equals() evaluates to the
21comparison of values in the objects.