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
- Learn: Declaring Strings
- Learn: Constructing a String
- Learn: Introduction to String Indexing
- Learn: Comparing Two String Objects Using compareTo Methods
- Learn: Comparing String Objects with equals Methods
- Learn: Obtaining Substrings from a String Object
- Learn: Using the split method on a String
- Practice: Evaluating Expressions that use the String Class
- Practice: Writing Code Using the String Class
- FRQ Practice: AP Computer Science A FRQ 1 Formatting Words
- FRQ Practice: AP Computer Science A FRQ 1 Sentence Analysis