The switch Statement (Cont.)


Expression can be of type byte, short, int, char, String, or an enumeration. Dulplicate case values are not allowed. The default statement is optional. The break statement is used inside the switch to terminate a statement sequence and is optional. If omitted, execution will continue on into the next case.
SwitchCaseDemo.java (the switch case statement)
// Java program to illustrate switch-case 
class SwitchCaseDemo { 
  public static void main( String args[ ] ) { 
    int no1 = Integer.parseInt( args[0] );
    int no2 = Integer.parseInt( args[1] );
    switch ( no1 - no2 ) {
      case no1:
        System.out.print( no1 );
        break;
      case 1:
        System.out.print( no2 );
        break;
      case 2:
        System.out.print( 2 );
        break;
      default:
        System.out.print( 3 );
        break;
    }
  }
}
  shell> java SwitchCaseDemo    

  Output:

        Result:

The break Keyword
When Java reaches a break keyword, it breaks out of the switch block. This will stop the execution of more code and case testing inside the block. When a match is found, and the job is done, it is time for a break. There is no need for more testing. A break can save a lot of execution time because it “ignores” the execution of all the rest of the code in the switch block.

The default Keyword
The default keyword specifies some code to run if there is no case match. Note that if the default statement is used as the last statement in a switch block, it does not need a break.