Java Reference
In-Depth Information
When a break statement is executed here, it causes execution to continue with the statement following
the closing brace for the switch . The break is not mandatory as the last statement for each case, but if you
don't put a break statement at the end of the statements for a case, the statements for the next case in se-
quence are executed as well, through to whenever another break is found or the end of the switch block is
reached. This is not usually what you want. The break after the default statements in the example is not
strictly necessary, but it does protect against the situation when you might add another case label at the end
of the switch statement block and overlook the need for the break at the end of the last case.
You need a case label for each choice to be handled in the switch , and the case values must all be dif-
ferent. The default case you have in the preceding example is, in general, optional. As I said, it is selected
when the value of the expression for the switch does not correspond with any of the case values that you
have defined. If you don't specify a default case and the value of the switch expression does not match
any of the case labels, none of the statements in the switch are executed, and execution continues at the
statement following the closing brace of the switch statement.
You could rewrite the previous switch statement to use a variable of an enumeration type as the expres-
sion controlling the switch . Suppose you have defined the WashChoice enumeration type like this:
enum WashChoice { cotton, linen, wool } // Define enumeration type
You can now code the switch statement like this:
WashChoice wash = WashChoice.linen; // Initial definition of variable
// Some more code that might change the value of wash...
switch(wash) {
case cotton:
System.out.println("Cotton selected");
// Set conditions for cotton...
break;
case linen:
// Set conditions for linen...
System.out.println("Linen selected");
break;
case wool:
System.out.println("Wool selected");
// Set conditions for wool...
break;
}
The switch is controlled by the value of the wash variable. Note how you use the enumeration constants
as case values. You must write them without the enumeration type name as a qualifier in this context; oth-
erwise, the code does not compile. Using enumeration constants as the case values makes the switch much
more self-explanatory. It is perfectly clear what each case applies to. Because you cannot assign a value to
a variable of an enumeration type that is not a defined enumeration constant, it is not necessary to include a
default case here.
Here's how you could write the switch statement to use an expression that results in a string:
switch(wash.toLowerCase()) {
case "cotton":
System.out.println("Cotton selected");
// Set conditions for cotton...
break;
Search WWH ::




Custom Search