Question 12
Back to Exercise
What is the output of the following Java program?
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!