Java Reference
In-Depth Information
else if (operation == '-')
subtract(object1, object2);
else if (operation == '*')
multiply(object1, object2);
else if (operation == '/')
divide(object1, object2);
This use of
if
statements is called a
nested
if
statement because each
else
statement
contains another
if
until all possible tests have been made.
In some languages, a shorthand mechanism that you can use for nested
if
statements is
to group tests and actions together in a single statement. In Java, you can group actions
together with the
switch
statement. The following example demonstrates
switch
usage:
switch (grade) {
case 'A':
System.out.println(“Great job!”);
break;
case 'B':
System.out.println(“Good job!”);
break;
case 'C':
System.out.println(“You can do better!”);
break;
default:
System.out.println(“Consider cheating!”);
4
}
A
switch
statement is built on a test variable; in the preceding example, the variable is
the value of the
grade
variable, which holds a
char
value.
The test variable, which can be the primitive types
byte
,
char
,
short
, or
int
, is com-
pared in turn with each of the
case
values. If a match is found, the statement or state-
ments after the test are executed.
If no match is found, the
default
statement or statements are executed. Providing a
default
statement is optional—if it is omitted and there is no match for any of the
case
statements, the
switch
statement might complete without executing anything.
The Java implementation of
switch
is limited—tests and values can be only simple
primitive types that can be cast to an
int
. You cannot use larger primitive types such as
long
or
float
, strings, or other objects within a
switch
, nor can you test for any rela-
tionship other than equality. These restrictions limit
switch
to the simplest cases. In con-
trast, nested
if
statements can work for any kind of test on any possible type.