Switch statements are shorthands for a certain kind of
if
statement. It is not uncommon to see a stack of
if
statements all relate to the same quantity like this:
if (x == 0) doSomething0();
else if (x == 1) doSomething1();
else if (x == 2) doSomething2();
else if (x == 3) doSomething3();
else if (x == 4) doSomething4();
else doSomethingElse();
Java has a shorthand for these types of multiple if
statements, the switch-case
statement. Here's how
you'd write the above using a switch-case
:
switch (x) {
case 0:
doSomething0();
break;
case 1:
doSomething1();
break;
case 2:
doSomething2();
break;
case 3:
doSomething3();
break;
case 4:
doSomething4();
break;
default:
doSomethingElse();
}
In this fragment x
must be a variable or expression
that can be cast to an int
without loss of precision.
This means the variable must be or the expression must return an
int
, byte
, short
or
char
. x
is compared with the value of each the
case
statements in succession until one matches. This
fragment compares x
to literals, but these too could
be variables or expressions as long as the variable or result of
the expression is an int
, byte
,
short
or char
. If no cases are matched, the
default action is triggered.
Once a match is found, all subsequent statements are executed
until the end of the switch
block is reached or you
break out of the block. This can trigger decidedly unexpected
behavior. Therefore it is common to include the break
statement at the end of each case block. It's good programming
practice to put a break
after each one unless you
explicitly want all subsequent statements to be executed.
It's important to remember that the switch
statement doesn't end when one case is matched and its action
performed. The program then executes all statements that follow in
that switch
block until specifically told to
break.