Bird
Raised Fist0

What will be printed when the following Java code executes?

medium📝 Analysis Q4 of Q15
LLD - Behavioral Design Patterns — Part 1
What will be printed when the following Java code executes?
interface Strategy { void execute(); }
class StrategyX implements Strategy { public void execute() { System.out.println("X"); } }
class StrategyY implements Strategy { public void execute() { System.out.println("Y"); } }
class Context {
private Strategy strategy;
public Context(Strategy strategy) { this.strategy = strategy; }
public void run() { strategy.execute(); }
}
public class Main {
public static void main(String[] args) {
Context context = new Context(new StrategyY());
context.run();
}
}
AX
BCompilation error
CY
DNo output
Step-by-Step Solution
Solution:
  1. Step 1: Identify which strategy is used

    The Context is initialized with new StrategyY().
  2. Step 2: Understand what run() does

    It calls strategy.execute(), which invokes StrategyY's execute method.
  3. Step 3: Output of StrategyY's execute

    StrategyY prints "Y" to the console.
  4. Final Answer:

    Y -> Option C
  5. Quick Check:

    Context uses StrategyY, prints Y [OK]
Quick Trick: Context runs chosen strategy's execute method [OK]
Common Mistakes:
MISTAKES
  • Confusing StrategyX and StrategyY
  • Assuming compilation error due to interface
  • Thinking no output occurs

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes