LearnFrenzy
Sign in Take a free test

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

A switch expression over an enum Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following Java program?

Main.java
enum Plan { FREE, BASIC, PRO, ENTERPRISE }

public class Main {
    static int price(Plan p) {
        return switch (p) {
            case FREE -> 0;
            case BASIC -> 199;
            case PRO -> 499;
            case ENTERPRISE -> 2999;
        };
    }

    public static void main(String[] args) {
        int total = 0;
        for (Plan p : new Plan[]{Plan.PRO, Plan.FREE, Plan.BASIC, Plan.PRO}) total += price(p);
        System.out.println(total + " " + price(Plan.valueOf("ENTERPRISE")));
    }
}
  • A 1197 2999 Correct
  • B 1196 2999
  • C 698 2999
  • D Compilation error: missing default
Correct Answer: Option A

499 + 0 + 199 + 499 = 1197. The switch covers every constant, so no default is needed.

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