Unit 1 Cycle 2 Day 11: equals() vs equalsIgnoreCase() Traps
Share
equals() vs equalsIgnoreCase() Traps
Section 1.11 — Strings: Comparison
Key Concept
The equalsIgnoreCase() method compares strings without considering letter case, while equals() is case-sensitive. The AP exam creates traps by combining these with other string operations: s.substring(0,1).equals("A") only matches uppercase A, while s.substring(0,1).equalsIgnoreCase("A") matches both. Another trap involves calling these methods on a null reference — always check which object calls the method. If str might be null, "expected".equals(str) is safer than str.equals("expected").
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) false true true
Three different comparison methods:
r1: "Hello".equals("hello") is false. equals() is case-sensitive. 'H' and 'h' are different.
r2: "Hello".equalsIgnoreCase("HELLO") is true. Ignoring case, both are the same word.
r3: "hello".compareTo("HELLO"). Lowercase letters have higher Unicode values than uppercase. 'h' is 104, 'H' is 72. So 104 - 72 = 32, which is positive. 32 > 0 is true.
Why Not the Others?
(B) equals() is case-sensitive. "Hello" and "hello" differ in the first character.
(C) compareTo() uses Unicode values. Lowercase 'h' (104) is greater than uppercase 'H' (72), so the result is positive, making r3 true.
(D) equalsIgnoreCase() specifically ignores case, so "Hello" and "HELLO" are considered equal.
Common Mistake
In Unicode/ASCII, all uppercase letters (65-90) come before all lowercase letters (97-122). So "hello".compareTo("HELLO") is positive because lowercase has higher values. This means lowercase strings are "greater than" uppercase strings in compareTo.
AP Exam Tip
Remember the Unicode ordering: digits (48-57) < uppercase (65-90) < lowercase (97-122). You do not need to memorize exact values, just know that uppercase comes before lowercase in compareTo.