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

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