LearnFrenzy
Sign in Take a free test

Control Flow Statements · Find the Error · Question 4

Error: a switch expression without default Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
public class Main {
    public static void main(String[] args) {
        int status = 2;
        String label = switch (status) {
            case 1 -> "new";
            case 2 -> "paid";
            case 3 -> "shipped";
        };
        System.out.println(label);
    }
}
  • A Arrows need braces
  • B A switch expression must be exhaustive; int has many other values, so a default arm is required Correct
  • C label must be var
  • D status must be an enum
Correct Answer: Option B

Add default -> "unknown"; – or switch on an enum and cover every constant.

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