AP® Computer Science A · Unit 1 · Topic 1.15
equals, ==, and compareTo for Strings
== compares two String references (are they the same object in memory?) while equals compares the actual characters. compareTo compares characters in order and returns a number showing which string comes first alphabetically.
A String variable doesn't hold text directly. It holds a reference, the address of an object sitting on the heap. == checks whether two references point at the exact same object. equals opens up both objects and checks whether their characters match, position by position. Two strings can look identical on screen and still fail == if they live at different addresses — they're equal in content but not identical in identity.
This is why new String("hi") is dangerous. Writing new always builds a fresh object on the heap, even if an identical string already exists somewhere. So a brand new object and some other "hi" will never share an address, and == reports false, even though the characters match and equals reports true. String literals behave differently: Java pools them, so two literals with the same text often share one object, making == accidentally return true. That coincidence is the trap.
compareTo settles order, not just equality. It walks both strings character by character, comparing character codes, and stops at the first difference, returning a positive number, a negative number, or zero based on that difference. "apple".compareTo("banana") is negative because 'a' comes before 'b'. This connects to the bigger theme of the unit: Strings are objects living on the heap, so comparing them correctly means understanding references and calling methods, not just writing simple symbols.
Key terms
- reference
- The address stored in a variable that points to where an object actually lives on the heap.
- ==
- An operator that checks whether two references point to the exact same object, not whether their contents match.
- equals
- A method that compares the actual characters inside two String objects and returns true if every character matches.
- compareTo
- A method that compares strings character by character and returns a negative, zero, or positive number showing their alphabetical order.
- string pool
- A storage area where Java reuses one object for identical string literals, which can make == misleadingly return true.
Watch it explained
- How it worksHow does == compare two addresses while equals compares the characters themselves?
- Worked exampleTrace String a = new String("hi"); String b = "hi"; and find what a == b and a.equals(b) give.
- Worked exampleFind what "apple".compareTo("banana") returns and what the sign of the answer means.
- How it worksHow does compareTo walk two strings character by character until they finally differ?
- Common mistakeWhy isn't == safe for strings even when it seems to work in small test programs?
Check yourself
End of topic.