1

I was learning Java online and came to the lesson on switch. To fool around, I remove one of the breaks after a particular case (which would be executed). I had thought that it would then check the next case, see that the condition is false, and skip to the default case before exiting. Instead, it executed the incorrect case and broke before the default case.

What went wrong here?

public class Switch {
    public static void main(String[] args) {

        char penaltyKick = 'R';

        switch (penaltyKick) {

            case 'L': System.out.println("Messi shoots to the left and scores!");
                                break; 
            case 'R': System.out.println("Messi shoots to the right and misses the goal!");

            case 'C': System.out.println("Messi shoots down the center, but the keeper blocks it!");
                                break;
            default:
                System.out.println("Messi is in position...");

        }

    }
}

Edit: Forgot to mention. The output was:

Messi shoots to the right and misses the goal! 
Messi shoots down the center, but the keeper blocks it!

1 Answers1

6

If you have a missing break, execution will fall through to the next case without checking the condition again. See here:

The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.

Vlad
  • 17,655
  • 4
  • 40
  • 70