Remember to use break in switch

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!”);
}
}

At first, I thought the execution order as below:

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

Test result not matched

However, the test result does not match my expectation:

This is B!
This is C!
This is D!

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:

Correction

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

Output:

This is B!

Leave a Reply

Your email address will not be published. Required fields are marked *