1Z0-809 · Question #129
Given the code fragment: 7. StringBuilder sb1 = new StringBuilder("Duke"); 8. String str1 = sb1.toString(); 9. // insert code here 10. System.out.print(str1 == str2); Which code fragment, when…
The correct answer is B. String str2 = str1. Option B works because str2 = str1 makes both variables point to the same object in memory - == on objects checks reference identity (same address), not value equality, so two references to the same object always return true. Why the distractors fail: A (sb1.toString() again)…
Question
Options
- AString str2 = sb1.toString();
- BString str2 = str1;
- CString str2 = "Duke";
- DString str2 = new String(str1);
How the community answered
(25 responses)- A12% (3)
- B76% (19)
- C8% (2)
- D4% (1)
Explanation
Option B works because str2 = str1 makes both variables point to the same object in memory - == on objects checks reference identity (same address), not value equality, so two references to the same object always return true.
Why the distractors fail:
- A (
sb1.toString()again) -toString()creates a newStringobject each call, sostr1andstr2point to different heap objects even though their content is identical. - C (
"Duke"literal) - String literals live in the string pool, butstr1was created viatoString()which allocates a new heap object outside the pool; the two objects are not the same reference. - D (
new String(str1)) - Thenewkeyword explicitly creates a fresh heap object, so it can never be==tostr1even though it copies the content.
Memory tip: Think of == as asking "are these the same physical box?" and .equals() as asking "do these boxes contain the same thing?" - only assignment (str2 = str1) guarantees both variables point to the exact same box.
Community Discussion
No community discussion yet for this question.