AP Computer Science A · Unit 2: Selection & Iteration
2.7 Comparing Objects
== compares references, not content
For object variables, the == operator checks whether two references point to the same object in memory, not whether their data is equal. Two different `String` objects with identical characters can be `==` false, even though their contents look the same.
equals() compares values
The .equals() method is used to compare the actual content of objects, like two `String` objects for identical characters. `String` overrides `.equals()` for this purpose. Always use `.equals()` when checking if two objects have the same value.
compareTo() for ordering
The .compareTo() method compares objects for relative order, returning a negative number, zero, or a positive number. For `String`, it uses lexicographic (dictionary-like) order based on Unicode values. `a.compareTo(b)` returns negative if `a` comes before `b`, zero if equal, positive if `a` comes after `b`.
Key terms
- == (for objects)
- Checks whether two references point to the same object in memory (reference equality).
- .equals()
- Method that compares the actual content/value of two objects; String overrides it for character comparison.
- .compareTo()
- Method that returns a negative, zero, or positive number indicating relative order; used for Strings in lexicographic order.
- Lexicographic order
- Dictionary-like ordering of Strings based on the Unicode values of their characters.
- new String("cat") == new String("cat")
- false — they are two distinct objects in memory, even though their content is identical.
Try an AP-style question
Code
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b);What is printed?
- hi
- An error
- false
- true
Show the answer
C. Different objects.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 2.7 free in APrep