Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need break after case statements?

Why doesn't the compiler automatically put break statements after each code block in the switch? Is it for historical reasons? When would you want multiple code blocks to execute?

like image 286
unj2 Avatar asked Apr 25 '10 22:04

unj2


2 Answers

Sometimes it is helpful to have multiple cases associated with the same code block, such as

case 'A': case 'B': case 'C':     doSomething();     break;  case 'D': case 'E':     doSomethingElse();     break; 

etc. Just an example.

In my experience, usually it is bad style to "fall through" and have multiple blocks of code execute for one case, but there may be uses for it in some situations.

like image 151
WildCrustacean Avatar answered Nov 07 '22 14:11

WildCrustacean


Java comes from C and that is the syntax from C.

There are times where you want multiple case statements to just have one execution path. Below is a sample that will tell you how many days in a month.

class SwitchDemo2 {     public static void main(String[] args) {          int month = 2;         int year = 2000;         int numDays = 0;          switch (month) {             case 1:             case 3:             case 5:             case 7:             case 8:             case 10:             case 12:                 numDays = 31;                 break;             case 4:             case 6:             case 9:             case 11:                 numDays = 30;                 break;             case 2:                 if ( ((year % 4 == 0) && !(year % 100 == 0))                      || (year % 400 == 0) )                     numDays = 29;                 else                     numDays = 28;                 break;             default:                 System.out.println("Invalid month.");                 break;         }         System.out.println("Number of Days = " + numDays);     } } 
like image 29
Romain Hippeau Avatar answered Nov 07 '22 14:11

Romain Hippeau