LearnFrenzy
Sign in Take a free test

Records, Enums and Sealed Classes · Predict the Output · Question 12

An exhaustive switch over sealed records Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 12 Back to Exercise

What is the output of the following Java program?

Main.java
sealed interface Expr permits Num, Add, Mul { }
record Num(int value) implements Expr { }
record Add(Expr l, Expr r) implements Expr { }
record Mul(Expr l, Expr r) implements Expr { }

public class Main {
    static int eval(Expr e) {
        return switch (e) {
            case Num n -> n.value();
            case Add a -> eval(a.l()) + eval(a.r());
            case Mul m -> eval(m.l()) * eval(m.r());
        };
    }

    public static void main(String[] args) {
        Expr e = new Add(new Num(2), new Mul(new Num(3), new Add(new Num(4), new Num(1))));
        System.out.println(eval(e) + " " + eval(new Mul(new Num(6), new Num(7))));
    }
}
  • A 17 42 Correct
  • B 25 42
  • C 15 42
  • D Compilation error
Correct Answer: Option A

2 + 3 × (4 + 1) = 17. The sealed interface lets the compiler confirm the switch is complete.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links