So this will be short and to the point.
switch ( expr )
{
case literal 1:
case literal 1 body
case literal 2:
case literal 2 body
case literal 3:
case literal 3 body
default:
default body
}
Unlike if statements which contain a condition in the
parentheses, switch contains an expression. This
expression must be type int or char. That's
already a limitation.
int x = 4 ;
switch ( x )
{
case 2:
System.out.println( "TWO" ) ;
break ;
case 4:
System.out.println( "FOUR" ) ;
break ;
case 6:
System.out.println( "SIX" ) ;
break ;
default:
System.out.println( "DEFAULT" ) ;
}
This evaluates x to 4. It skips case 2 since the value
4 doesn't match 2. It does match case 4. It runs the body
and prints "TWO". Then it runs break and exits the
switch.
Let's see what happens when you leave it out.
int x = 4 ;
switch ( x )
{
case 2:
System.out.println( "TWO" ) ;
case 4:
System.out.println( "FOUR" ) ;
case 6:
System.out.println( "SIX" ) ;
default:
System.out.println( "DEFAULT" ) ;
}
This prints out:
FOUR SIX DEFAULTThat's probably not what the user had in mind. Without the break, each time a body runs, it falls through and starts running the next body, and the next, after it matches the correct case.
This is supposed to be a feature of switch. You can combine cases together.
int x = 4 ;
switch ( x )
{
case 1:
case 3:
case 5:
System.out.println( "ODD" ) ;
break ;
case 2:
case 4:
case 6:
System.out.println( "EVEN" ) ;
break ;
default:
System.out.println( "DEFAULT" ) ;
}
In this example, falling through for case 1 and case 3
is correct, but we still needed a break at the end
int x = 4 ;
switch ( x )
{
case (x % 2 == 1): // WRONG!
System.out.println( "ODD" ) ;
break ;
case (x % 2 == 0): // WRONG!
System.out.println( "EVEN" ) ;
break ;
default:
System.out.println( "DEFAULT" ) ;
}