Difficulty: Easy
Correct Answer: 2 and 4
Explanation:
Introduction / Context:
The instanceof
operator tests whether a reference refers to an instance compatible with a given type. This question focuses on syntax correctness and type positions around instanceof
, not on the runtime result.
Given Data / Assumptions:
Concept / Approach:
The left operand of instanceof
must be a reference expression; the right operand must be a type. The operator itself is a keyword, not a method. Supertype/superclass relationships make both t instanceof Ticker
and t instanceof Component
legal.
Step-by-Step Solution:
(Component instanceof t)
→ illegal: left side is a type, not an expression; right side is a variable name. Reject.2) (t instanceof Ticker)
→ legal: reference vs type.3) t.instanceof(Ticker)
→ illegal: instanceof
is not a method.4) (t instanceof Component)
→ legal: Ticker is-a Component.
Verification / Alternative check:
Compiling with lines 2 and 4 produces booleans; running would yield true
for both with a fresh Ticker.
Why Other Options Are Wrong:
instanceof
.
Common Pitfalls:
Attempting to put a class type on the left-hand side or treating instanceof
like a method call.
Final Answer:
2 and 4
Discussion & Comments