Java instanceof evaluation order: with Tree tree = new Pine(), which branch executes and what is printed?\n\nclass Tree {}\nclass Pine extends Tree {}\nclass Oak extends Tree {}\npublic class Forest1 {\n public static void main (String [] args) {\n Tree tree = new Pine();\n if (tree instanceof Pine)\n System.out.println("Pine");\n else if (tree instanceof Tree)\n System.out.println("Tree");\n else if (tree instanceof Oak)\n System.out.println("Oak");\n else\n System.out.println("Oops");\n }\n}

Difficulty: Easy

Correct Answer: Pine

Explanation:


Introduction / Context:
This code tests runtime type checks using instanceof and the impact of ordering in an if/else-if chain. The declared type is Tree, but the actual (runtime) type is Pine, a subclass of Tree.


Given Data / Assumptions:

  • tree is declared as Tree but constructed as new Pine().
  • instanceof checks are ordered: Pine, then Tree, then Oak.
  • Only the first true branch executes in an if/else-if chain.


Concept / Approach:
instanceof tests the runtime type. A Pine object is also a Tree due to inheritance, but the first condition explicitly checks Pine and therefore succeeds before reaching the broader Tree check.


Step-by-Step Solution:
Evaluate tree instanceof Pine → true. Print "Pine". Remaining else-if blocks are skipped.


Verification / Alternative check:
If the order were reversed (Tree first), it would print "Tree" because that condition would capture all subclasses too. Ordering matters.


Why Other Options Are Wrong:
"Tree" would be printed only if the first condition did not match or if it appeared first. "Oak"/"Forest"/"Oops" do not apply to a Pine instance.


Common Pitfalls:
Thinking declared type governs instanceof; forgetting that only the first true condition in an if/else-if chain executes.


Final Answer:
Pine

More Questions from Java.lang Class

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion