Java Reference
In-Depth Information
Example 1−6: FizzBuzz2.java (continued)
break;
case 7: case 14: case 21: case 28: // For any multiple of 7...
System.out.print("buzz ");
// print "buzz".
break;
default:
// For any other number...
System.out.print(i + " ");
// print the number.
break;
}
}
System.out.println();
}
}
The
switch
statement acts like a switch operator at a busy railyard, switching a
train (or the execution of a program) to the appropriate track (or piece of code)
out of many potential tracks. A
switch
statement is often an alternative to repeated
if/else
statements, but it only works when the value being tested is a primitive
integral type (e.g., not a
double
or a
String
) and when the value is being tested
against constant values. The basic syntax of the
switch
statement is:
switch(
expression
){
statements
}
The
switch
statement is followed by an
expression
in parentheses and a block of
code in curly braces. After evaluating the
expression
, the
switch
statement exe-
cutes certain code within the block, depending on the integral value of the expres-
sion. How does the
switch
statement know where to start executing code for
which values? This information is indicated by
case:
labels and with the special
default:
label. Each
case:
label is followed by an integral value. If the
expres-
sion
evaluates to that value, the
switch
statement begins executing code immedi-
ately following that
case:
label. If there is no
case:
label that matches the value of
the expression, the
switch
statement starts executing code following the
default:
label, if there is one. If there is no
default:
label,
switch
does nothing.
The
switch
statement is an unusual one because each case doesn't have its own
unique block of code. Instead,
case:
and
default:
labels simply mark various
entry points into a single large block of code. Typically, each label is followed by
several statements and then a
break
statement, which causes the flow of control to
exit out of the block of the
switch
statement. If you don't use a
break
statement at
the end of the code for a label, the execution of that case “drops through” to the
next case. If you want to see this in action, remove the
break
statements from
Example 1-6 and see what happens when you run the program. Forgetting
break
statements within a
switch
statement is a common source of bugs.
Computing Factorials
The factorial of an integer is the product of that number and all of the positive
integers smaller than it. Thus the factorial of 5, written
5!
, is the product
5*4*3*2*1
, or 120. Example 1-7 shows a class,
Factorial
, that contains a method,
factorial()
, that computes factorials. This class is not a program in its own right,
but the method it defines can be used by other programs. The method itself is