touque.ca > Education Commons > Java > Resources > Control

Selection: switch

In versions before Java 7, the switch statement works only with integer datatypes: byte, short, int, and char.

Since Java 7, the switch statement works with those integer datatypes and also

A switch statement is composed of an expression and a block. The expression must be of one of the datatypes identified above.

switch compares an expression to zero or more case labels, each identified with the case keyword. If the expression matches the case label, all statements following the label are executed—even those statements labelled as other cases.

Since we often want the execution only of the statements labelled by a particular case, we place the break statement at the end of each case. break causes the immediate termination of the switch statement; execution continues with the first statement following the switch block.

An optional special case, identified with the default keyword, is executed if the expression doesn’t match any other case.

To the extent allowed by your IDE, the switch statement should be formatted as shown below.

BlueJ screenshot of properly formatted switch statement

This page drawn from The switch Statement (The Java Tutorials) retrieved 2015-12-31.

touque.ca > Education Commons > Java > Resources > Control

[This page last updated 2020-12-23 at 12h13 Toronto local time.]