+ 2

Clarify Java switch statement

I'm just starting with Java. The following code is copied from one of the lessons with the 'break' commented out of the first 2 case statements. I don't understand why the case 2 and 3 printlines are executed as '1' is not '2' or '3'. I come from a long background of VBA (more recently SQL as well). In VBA and SQL you don't need a 'break'. At first glance it appears the case statement is not doing anything. What am I missing please? https://code.sololearn.com/cH94X6e0sWbq/?ref=app

14th Dec 2017, 12:03 PM
Duncan
Duncan - avatar
4 odpowiedzi
+ 12
Without the break statements, 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. It is typically used to define common action for multiple cases.
14th Dec 2017, 6:57 AM
Dev
Dev - avatar
+ 5
Without the break statement the code will fall through to the next statement below it until it hits a break statement or reaches the end of the switch. So unless you intend to group certain cases together always use a break statement at the end of each statement.
14th Dec 2017, 6:55 AM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Thanks folks. Just seems a foreign concept based on my past history. Will have to take care with Java :) Any examples where not using the break would be useful?
14th Dec 2017, 7:11 AM
Duncan
Duncan - avatar
+ 3
As said above, you might want the same thing to happen for multiple cases: case A: case B: case C: // code break; so A and B don't have a break. Also you might want something like this case INACTIVE: // initialize case ACTIVE: // execute break; so when this code is called any inactive items are initialized and then executed, but active items are just executed because they don't need to be initialized. The deliberate fall through allows the execute statement to be used by both cases. Though for the sake of convention and clarity, I might be inclined to just put the execute in the first case with a break anyway.
14th Dec 2017, 7:54 AM
Dan Walker
Dan Walker - avatar