nerdexam
Oracle

1Z0-803 · Question #210

Given: Which code fragment, when inserted at line 14, enables the code to print Mike Found?

The correct answer is D. int f = ps.indexOf(p2);. To enable the code to print 'Mike Found', the indexOf method must be called with an object reference that is present in the ps list.

Working with Selected Classes from the Java API

Question

Given:

Which code fragment, when inserted at line 14, enables the code to print Mike Found?

Exhibit

1Z0-803 question #210 exhibit

Options

  • Aint f = ps.indexOf {new patient ("Mike")};
  • Bint f = ps.indexOf (patient("Mike"));
  • Cpatient p = new Patient ("Mike");
  • Dint f = ps.indexOf(p2);

How the community answered

(31 responses)
  • A
    10% (3)
  • B
    3% (1)
  • C
    19% (6)
  • D
    68% (21)

Why each option

To enable the code to print 'Mike Found', the `indexOf` method must be called with an object reference that is present in the `ps` list.

Aint f = ps.indexOf {new patient ("Mike")};

This fragment contains a syntax error (`{{ }}`) and, even if corrected to `new Patient("Mike")`, it would create a new object instance. Without `equals()` overridden in `Patient` to compare content, `indexOf` would likely return -1 as it compares object references.

Bint f = ps.indexOf (patient("Mike"));

This fragment contains a syntax error (`patient("Mike")` instead of `new Patient("Mike")`). Even if fixed, it would create a new object instance, which typically would not be found by reference comparison if `equals()` is not overridden.

Cpatient p = new Patient ("Mike");

This fragment only creates a new `Patient` object `p` but does not perform an `indexOf` operation on the `ps` list or assign a value to a variable `f`, so it does not directly enable the desired print statement.

Dint f = ps.indexOf(p2);Correct

The `indexOf` method in Java's `List` interface, when called with an object `p2`, checks for object identity (using `==`) unless the `equals` method is overridden. If `p2` refers to an existing `Patient` object already added to the `ps` list, `indexOf(p2)` will correctly return its index, enabling the 'Mike Found' message.

Concept tested: Java List.indexOf method, object identity

Source: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html#indexOf(java.lang.Object)

Topics

#ArrayList#indexOf method#object equality#custom objects

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice