DEV Community

Cover image for Difference Between == and equals() in Java
Arul .A
Arul .A

Posted on

Difference Between == and equals() in Java

What is ==?

  • The operator is used reference comparison.
  • It compares whether two variables refer to the same object in memory.

Example:

String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1 == s2);
Enter fullscreen mode Exit fullscreen mode

Output:

false
Enter fullscreen mode Exit fullscreen mode

Here, s1 and s2 contain the same text, but they are stored in different memory locations. Therefore, == returns false.

What is equals()?

  • The equals() method compares the actual content or values of two objects.

Example:

String s1 = new String("Java");
String s2 = new String("Java");

System.out.println(s1.equals(s2));
Enter fullscreen mode Exit fullscreen mode

Output:

true
Enter fullscreen mode Exit fullscreen mode

The content of both strings is "Java", so equals() returns true.

Top comments (0)