Skip Top Navigation Bar

Comparing Strings with equals() - Example 2

Snippet: Comparing Strings with equals()

Explanation

This snippet shows that equals() is case-sensitive. Even though "Hello", "hello", and "HELLO" all contain the same letters, they are not considered equal because their characters differ in case. Both comparisons return false.

This is important to keep in mind whenever you compare strings that may come from user input or mixed-case sources — a difference in capitalisation is enough to make equals() return false.

What You Can Do

Try using equalsIgnoreCase() instead of equals(). Does it return true for all three comparisons? This method is useful when case should not matter for the comparison.

You can also try comparing "Hello" with "Hello " (with a trailing space). What does equals() return? Even a single extra space makes the strings unequal — something to watch out for in real programs.

Run it and observe the output!

Example List

Additional Resources