Skip Top Navigation Bar
Current Tutorial
Finding the Index of a String in Another String

Finding the Index of a String in Another String

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!


Last update: May 1, 2026


Current Tutorial
Finding the Index of a String in Another String