Java Reference
In-Depth Information
56. Finish every set of statements associated with a case label with a
break statement
A switch block comprises several case labels and an optional but highly recommended
default label. Statements that follow each case label must end with a break statement,
which is responsible for transferring the control to the end of the switch block. When
omitted, the statements in the subsequent case label are executed. Because the break
statement is optional, omitting it produces no compiler warnings. When this behavior is
unintentional, it can cause unexpected control flow.
Noncompliant Code Example
Inthisnoncompliantcodeexample,thecasewherethe card is11lacksa break statement.
As a result, execution continues with the statements for card = 12 .
Click here to view code image
int card = 11;
switch (card) {
/* ... */
case 11:
System.out.println("Jack");
case 12:
System.out.println("Queen");
break;
case 13:
System.out.println("King");
break;
default:
System.out.println("Invalid Card");
break;
}
Compliant Solution
This compliant solution terminates each case with a break statement.
Click here to view code image
int card = 11;
switch (card) {
Search WWH ::




Custom Search