case 1: // no conflicts with outer switch
System.out.println("target is one");
case 2: // ...
Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in
the outer switch. The count variable is only compared with the list of cases at the outer level.
If count is 1, then target is compared with the inner list cases.
In summary, there are three important features of the switch statement to note:
The switch differs from the if in that switch can only test for equality, whereas if
can evaluate any type of Boolean expression. That is, the switch looks only for a
match between the value of the expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a
switch statement and an enclosing outer switch can have case constants in common.
A switch statement is usually more efficient than a set of nested ifs.
The last point is particularly interesting because it gives insight into how the Java compiler
works. When it compiles a switch statement, the Java compiler will inspect each of the case
constants and create a "jump table" that it will use for selecting the path of execution depending
on the value of the expression. Therefore, if you need to select among a large group of values,
a switch statement will run much faster than the equivalent logic coded using a sequence of
if-elses. The compiler can do this because it knows that the case constants are all the same type
and simply must be compared for equality with the switch expression. The compiler has no
such knowledge of a long list of if expressions.
Iteration Statements
Java's iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met. As you will see, Java has a loop to fit any
programming need.
The while loop is Java's most fundamental loop statement. It repeats a statement or block
while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop. The curly braces are unnecessary if only
a single statement is being repeated.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks