‘.equals()’ and ‘==’ what’s the Difference

Light
1 min readMay 31, 2024

--

In Java, the == operator compares object references rather than the content of the objects. In the code snippet you provided

public static void main(String[] args) {
System.out.println("Hello" == new String("Hello"));
}

Here’s a breakdown of what’s happening:

  1. "Hello": This is a string literal. In Java, string literals are interned, meaning they are stored in a common pool and reused.
  2. new String("Hello"): This creates a new String object with the same content as the string literal, but it is a different object in memory.

When you use == to compare these two, you're comparing their memory addresses (references), not their contents. Since "Hello" and new String("Hello") are different objects, their references are different, and the == comparison returns false.

Therefore, the output of the program will be

false

If you want to compare the actual contents of the strings, you should use the .equals() method:

public static void main(String[] args) {
System.out.println("Hello".equals(new String("Hello")));
}

This will compare the contents of the strings, and in this case, it will return true.

--

--

Light
Light

Written by Light

Upcoming CEO of "A" company

No responses yet