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.

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:

Correction

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

Output:

This is B! 

Enter fullscreen mode Exit fullscreen mode

原文链接:Remember to use break in switch

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
Do not let dream just be your dream.
别让梦想只停留在梦里
评论 抢沙发

请登录后发表评论

    暂无评论内容