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.
1Case1)
2String s1 = "Stack Overflow";
3String s2 = "Stack Overflow";
4s1 == s1; // true
5s1.equals(s2); // true
6Reason: String literals created without null are stored in the string pool in the permgen area of the heap. So both s1 and s2 point to the same object in the pool.
7Case2)
8String s1 = new String("Stack Overflow");
9String s2 = new String("Stack Overflow");
10s1 == s2; // false
11s1.equals(s2); // true
12Reason: If you create a String object using the `new` keyword a separate space is allocated to it on the heap.
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