Tag Archives: Control Structure

Switch hates me…

After all, my ignorance caused a complicated troubleshooting on an control structure of a Java method: a ‘break’ was missing. But what happened? Reason enough for some thoughts about the Switch Case syntax, something, we all, of course, know very well.

The following code

int x = 1;
switch (x) {
		
 case 1:
	System.out.println( "1" );
 case 2:
	System.out.println( "2" );
 case 3:
	System.out.println( "3" );
 default:
	System.out.println( "default" );
		
} // switched

prints on the command line:

$:
1
2
3
default

Changing the value of the variable x to 3, prints:

$:
3
default

Nothing changes, if you move the default block before the first case block, as long as the value of the switch variable is found in any case expression.

Only if the default block is before the first case block and the value of the switch variable is not found in any case expression, the default block and all case blocks will be executed, until a ‘break’ is found or the end of the switch structure is reached.

In short: If a ‘break’ statement is missing after a case block, all following case blocks will be executed, whether the case expression is true, or not. This continues until a ‘break’ or the end of the switch structure is reached and is called fall-through.

This behaviour is identical in PHP.