LearnFrenzy
Sign in Take a free test

Control Flow Statements · Find the Error · Question 8

Error: a pattern case dominated by an earlier case Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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

Main.java
public class Main {
    static String kind(Object o) {
        return switch (o) {
            case Number n -> "number";
            case Integer i -> "integer";
            default -> "other";
        };
    }

    public static void main(String[] args) {
        System.out.println(kind(5));
    }
}
  • A Integer cannot be a pattern
  • B Every Integer is a Number, so case Integer i can never be reached after case Number n; put the more specific case first Correct
  • C default must be first
  • D Patterns need a when guard
Correct Answer: Option B

javac: "this case label is dominated by a preceding case label".

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