Incremental Java
switch

switch

I really don't like switch. I find its use limited and awkward. Some like it for its brevity.

So this will be short and to the point.

Syntax

The syntax of a switch statement looks like:
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.

Semantics

The semantics of switch is:

An Example

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.

Problem 2: You need break

Most of the times, you must end each case with break. It's easy to forget, however. Both C and languages like Java made the mistake of forcing you to write a statement that should be there all the time.

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
DEFAULT
That'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

Problem 3: Can't use ranges

The case keyword has to be followed by a literal or a constant expression. It can't be a range or something that tests x
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" ) ;
}

Summary

I find using switch painful. It works on a limited number of types. You have to remember to use break. You can't use ranges. Some people like it for its ease of reading. That's personal preference. Use it if you like.