THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

the bottom of what used to be the last part of the switch when a new case is added.


All case labels must be enum constants or constant expressionsthe expressions must contain only literals or
named constants initialized with constant expressionsand must be assignable to the type of the switch
expression. In any single switch statement, each case value must be unique, and there can be at most one
default label.


When you use an enum as a switch expression, you will get no warning if you leave out a case. It is your job
to ensure that each case is covered. To safeguard against an enum being redefined to have additional
constants, you should always include a default case that simply throws an exception.


Only statements directly within the switch block can have case labels. This means that you cannot, for
example, transfer control to a statement within the switch block that is in the middle of a loop, or a statement
within a nested block of code. You can, however, skip the declaration and initialization of a local variable
within the switch block (not that we recommend it). The effect of this is that the local variable is still
considered to be declared, but the initializer has not been executed. Because local variables must be
initialized, any attempt to read the value of that variable will result in a compile-time errorthe first use of that
variable must be an assignment.


The first statement in a switch block must be labeled, otherwise it is unreachable (all cases will jump over it)
and your code will not compile.


Exercise 10.2: Rewrite your method from Exercise 10.1 to use a switch.


Exercise 10.3: Using your "days of the week" enum from Exercise 6.1 write a method that takes a day of the
week and returns TRue if it is a working day, and false otherwise. First use nested ifelse statements and
then a switch statement. Which do you think results in clearer code?


10.4. while and dowhile


The while loop looks like this:


while (expression)
statement


The expressionagain either of boolean or Boolean typeis evaluated and, if it is TRue, the statement
(which may be a block) is executed. Once the statement completes, the expression is reevaluated and, if still
TRue, the statement is executed again. This repeats until the expression evaluates to false, at which point
control transfers to after the while.


We introduced the while loop with our second program in Chapter 1, the Fibonacci program:


while (hi < MAX) {
System.out.println(hi);
hi = lo + hi;
lo = hi - lo;
}


This loops around printing and calculating new Fibonacci values until the highest value computed exceeds the

Free download pdf