Equals method vs == operator

Heeah
1 min readDec 30, 2023

--

Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator check memory location or address of two objects are the same or not whereas .equals() evaluates to the comparison of values in the objects.

public static void main(String[] args) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = new String("Hello");

System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1.equals(s2)); // true
System.out.println(s1.equals(s3)); // true
}

Primitives are basic types with a single value and don’t implement any methods. Therefore, it’s impossible to call the equals() method directly using primitives. However, since every primitive has its own wrapper class, we can use the boxing mechanism to cast it into its object representation. Then, we can easily call the equals() method.

        int a = 10;
int b = 10;
System.out.println(a == b); // true
System.out.println(a.equals(b)); // compilation error

Integer c = a;
System.out.println(c.equals(a)); // true

Reference
https://www.geeksforgeeks.org/difference-between-and-equals-method-in-java/
https://www.baeldung.com/java-equals-method-operator-difference

--

--