Java switch/case statement syntax

Posted September 7, 2004 by Rex in Java programming

The switch statement in Java provides a convenient method for branching a program based on a number of conditionals. This tech-recipe describes the use of the Java switch statement.


The basic format of a switch statement in Java is as follows:

switch (expression) {
case cond1: code_block_1;
case cond2: code_block_2;
...
case condn: code_block_n;
default: code_block_default;
}

where expression is an integral expression (such as int, char, short, or byte, but not long). In each case statement within the switch statement, a comparison is made which is equivalent to if (expression == cond1). If the comparison evaluates to true, the code within the block is executed. The final default: line is analogous to a final else statement.

This arrangement is similar to a cascade of if/else if/else if statements but with one substantial difference. At the end of each code block, an optional break statement alters the flow through the switch statement. Without any break statements, all subsequent code blocks will be executed once a true evaulation is found. To make a switch statement behave just like an if/else if/else if statement, always put break statements at the end of code blocks. However, leaving out break statements can provide a capability very difficult to achieve with if statements.

For example, consider the following code:

public class TestSwitch {

public final static int TITANIUM = 0;
public final static int PLATINUM = 1;
public final static int GOLD = 2;
public final static int SILVER = 3;
public final static int TIN = 4;

public static void main(String[] args) {
System.out.println("Tin -----");
printGift(TIN);
System.out.println("Titanium -----");
printGift(TITANIUM);
}

public static void printGift(int serviceLevel) {
switch(serviceLevel) {
case TITANIUM: case PLATINUM:
System.out.println(" Free toaster");
case GOLD:
System.out.println(" Free stapler");
case SILVER: case TIN:
System.out.println(" Free staple remover");
break;
default:
System.out.println("No gift");
}
}
}

The example demonstrates break usage since any match will cause one or more println commands to output text but will not print the “No gift” line from the default code block. In addition, note that multiple case statements can be placed before each code block. Running this sample code results in the following output:

Tin -----
Free staple remover
Titanium -----
Free toaster
Free stapler
Free staple remover

The Conversation

Follow the reactions below and share your own thoughts.