Remember to use break in switch

ivanyu2021

Ivan Yu

Posted on April 14, 2024

Remember to use break in switch

Recently, I introduced a bug because I forget to add break after case in switch. So, I wrote this blog to remind myself and hope that it can help the others not to make same mistake again.

Misunderstanding about switch

First, we look at following:

public static void main(String[] args) throws Exception {
  String input = "B";
  switch(input)
  {
    case "A":
      System.out.println("This is A!");
    case "B":
      System.out.println("This is B!");
    case "C":
      System.out.println("This is C!");
    case "D":
      System.out.println("This is D!");
  }
}
Enter fullscreen mode Exit fullscreen mode

At first, I thought the execution order as below:

  1. Since input is "B", it falls into condition case "B" and then print "This is B!".
  2. Since "B" does not match "C" and "D", nothing should be printed out afterward.

image

Test result not matched

However, the test result does not match my expectation:

This is B!
This is C!
This is D!
Enter fullscreen mode Exit fullscreen mode

According to geeks for geeks explanation for fall through condition in switch,

Fall through condition: This condition occurs in the switch control statement when there is no break keyword mention for the particular case in the switch statement and cause execution of the cases till no break statement occurs or exit from the switch statement.

i.e. When a case is matched, it continues to execute below case statements until:

  • There is a break OR
  • Exit from the switch statement

Actual execution:
image

Correction

Add break for each case, and the problem is resolved.

image

Output:

This is B!
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ivanyu2021
Ivan Yu

Posted on April 14, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related