1Z0-803 · Question #217
Given: Which code fragment, when inserted at line 9, enables the code to print true?
The correct answer is A. String str2 = str1;. The question asks which code fragment, when inserted at a specific line, will make a subsequent reference equality comparison between two String variables (str1 == str2) evaluate to true.
Question
Given:
Which code fragment, when inserted at line 9, enables the code to print true?
Options
- AString str2 = str1;
- BString str2 = new string (str1);
- CString str2 = sb1.toString();
- DString str2 = "Duke";
How the community answered
(25 responses)- A72% (18)
- B8% (2)
- C4% (1)
- D16% (4)
Why each option
The question asks which code fragment, when inserted at a specific line, will make a subsequent reference equality comparison between two String variables (`str1 == str2`) evaluate to true.
`String str2 = str1;` assigns the reference of `str1` to `str2`. This makes both `str1` and `str2` point to the exact same String object in memory, ensuring that `str1 == str2` (reference equality) evaluates to `true`.
`String str2 = new String (str1);` creates a new String object with the same content as `str1` but at a different memory location, so `str1 == str2` would be `false`.
Assuming `sb1` holds 'Duke', `sb1.toString()` creates a new String object, distinct from `str1`'s object, making `str1 == str2` `false`.
While `str2` would point to the interned 'Duke' literal, `str1` (if initialized as `new String("Duke")`) refers to a distinct object on the heap, so `str1 == str2` would be `false`.
Concept tested: Java String reference vs. content equality
Source: https://docs.oracle.com/javase/tutorial/java/data/strings.html
Topics
Community Discussion
No community discussion yet for this question.