AP CSA Unit 1 Day 21: Aliasing Two References To Same Object
Share
Advanced Practice Question
String s1 = "Java";
String s2 = new String("Java");
String s3 = s1;
Which of the following evaluate to true?
I. s1 == s2
II. s1 == s3
III. s1.equals(s2)
This tests the critical difference between == (reference equality) and .equals() (content equality).
I. s1 == s2 → false
s1 points to the String literal "Java" in the String pool. s2 was created with new String("Java"), which forces a new object in memory. Since == compares memory addresses and these are two different objects, the result is false.
II. s1 == s3 → true
s3 = s1 copies the reference. Both s1 and s3 now point to the exact same object in memory. == returns true when two variables reference the same object.
III. s1.equals(s2) → true
.equals() compares the contents of the Strings, character by character. Both contain "Java", so this returns true regardless of whether they are the same object.
Only II and III are true.
A) I and II only — Statement I is false. The new keyword always creates a separate object in memory, so s1 == s2 compares two different addresses and returns false.
C) I and III only — Statement I is false (see above). Statement II should be included because s3 = s1 makes them the same reference.
D) I, II, and III — Statement I is false. Using new String() creates a distinct object even when the content matches an existing String literal.
The key rule: == checks whether two variables hold the same memory address (point to the same object). .equals() checks whether two objects contain the same content. The new keyword always creates a brand-new object, guaranteeing a different memory address even if the content is identical to an existing object.
AP exam rule of thumb: always use .equals() to compare String content. Reserve == for checking whether two variables are literally the same object. When you see new String(...), immediately know that == with any other variable will be false, even if the characters are identical.
Keep Building Mastery!
Cycle 2 questions prepare you for the hardest AP CSA exam questions.
Study Games Practice FRQs