nerdexam
Oracle

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

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 inserted at line 9, enables the code to print true?

Options

  • AString str2 = sb1.toString();
  • BString str2 = str1;
  • CString str2 = "Duke";
  • DString str2 = new String(str1);

How the community answered

(25 responses)
  • A
    12% (3)
  • B
    76% (19)
  • C
    8% (2)
  • D
    4% (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 new String object each call, so str1 and str2 point to different heap objects even though their content is identical.
  • C ("Duke" literal) - String literals live in the string pool, but str1 was created via toString() which allocates a new heap object outside the pool; the two objects are not the same reference.
  • D (new String(str1)) - The new keyword explicitly creates a fresh heap object, so it can never be == to str1 even 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.

Full 1Z0-809 Practice