Skip Top Navigation Bar

Comparing Strings with == and equals() - Example 1

Snippet: Comparing Strings with == and equals()

Explanation

This snippet highlights one of the most important distinctions in Java: the difference between == and equals() when comparing strings.

== checks whether two variables point to the exact same object in memory. Since hello1 and hello2 are created with new String(), they are two separate objects — even though they contain the same characters. So hello1 == hello2 returns false.

equals(), on the other hand, compares the content of the strings character by character. Since both hold "Hello", hello1.equals(hello2) returns true.

What You Can Do

Try creating the two variables without new String(), using plain string literals: String hello1 = "Hello" and String hello2 = "Hello". Does == still return false? You might be surprised.

You can also try equals() with strings that differ only in case, like "Hello" and "hello". Does it return true or false? What about equalsIgnoreCase()?

Run it and observe the output!

Example List

Additional Resources