nerdexam
Oracle

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.

Working with Selected Classes from the Java API

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)
  • A
    72% (18)
  • B
    8% (2)
  • C
    4% (1)
  • D
    16% (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.

AString str2 = str1;Correct

`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`.

BString str2 = new string (str1);

`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`.

CString str2 = sb1.toString();

Assuming `sb1` holds 'Duke', `sb1.toString()` creates a new String object, distinct from `str1`'s object, making `str1 == str2` `false`.

DString str2 = "Duke";

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

#String class#object references#reference equality

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice