Comparing Strings: equals and compareTo

Part of: Using Objects

Never Compare Strings With == Because Strings are objects , == compares references (do the two variables point to the same object?), not the text. Two Strings with identical characters can live at different addresses, so == may surprisingly return false. To compare contents , use methods. equals equals returns a boolean : true when both Strings hold exactly the same characters, false otherwise. It is case-sensitive . Use equalsIgnoreCase when case should not matter. compareTo compareTo gives ordering information, returning an int : - negative if the caller comes before the argument alphabetically - zero if they are equal - positive if the caller comes after the argument Comparison is lexicographic : characters are compared by their Unicode values, left to right, until they differ. Uppercase letters (65-90) come before lowercase (97-122), so "Z".compareTo("a") is negative. Reading the Sign, Not the Number The AP exam cares about the sign of compareTo, not its exact magnitude. Write conditions like: Choosing the Right Tool - Need a yes/no "are these the same text?" - equals . - Need to sort or decide order - compareTo . - Almost never - == for Strings. Mixing these up is one of the m

Challenge: Alphabetical Order