Jump to content

Java Programming/Keywords/switch

From Wikibooks, open books for an open world

switch is a Java keyword.

It is a branching operation, based on a number. The 'number' must be either char, byte, short, or int primitive type.

Syntax:

switch ( <integer-var> )
{
   case <label1>: <statements>;
   case <label2>: <statements>;
   ...
   case <labeln>: <statements>;
   default: <statements>;
}

When the <integer-var> value match one of the <label>, then: The statements after the matched label will be executed including the following label's statements, until the end of the switch block, or until a break keyword is reached.

For example:

Computer code
int var = 3;
switch ( var )
{
   case 1: 
      System.out.println( "Case: 1" );
      System.out.println( "Execute until break" );
      break;		  	
   case 2: 
      System.out.println( "Case: 2" );
      System.out.println( "Execute until break" );
      break;
   case 3:
      System.out.println( "Case: 3" );
      System.out.println( "Execute until break" );
      break;  	
   case 4:
      System.out.println( "Case: 4" );
      System.out.println( "Execute until break" );
      break;      
   default:
      System.out.println( "Case: default" );
      System.out.println( "Execute until break" );
      break;	      
}

The output from the above code is:

Case: 3
Execute until break

The same code can be written with if-else blocks":

Computer code
int var = 3;
if ( var == 1 ) {
   System.out.println( "Case: 1" );
   System.out.println( "Execute until break" );
} else if ( var == 2 ) {
   System.out.println( "Case: 2" );
   System.out.println( "Execute until break" );
} else if ( var == 3 ) {
   System.out.println( "Case: 3" );
   System.out.println( "Execute until break" );
} else if ( var == 4 ) {
   System.out.println( "Case: 4" );
   System.out.println( "Execute until break" );
} else {
   // -- This is the default part -- 
   System.out.println( "Case: default" );
   System.out.println( "Execute until break" );
}


See also: