Two switch Statement Examples


Below give two code samples of switch statement.

SwitchStmt.java (the switch statement)
class SwitchStmt {
  public static void main( String args[ ] ) {
    int x = 10, y = 20, z = 30;
    switch ( 10+10 ) {
      case x:
        System.out.print( x );
        break;
      case y:
        System.out.print( y );
        break;
      case z:
        System.out.print( z );
        break;
      default:
        System.out.print( 40 );
        break;
    }
  }
}
Output:             Result:

Another example of the switch statement is given next:

BreakKeyword.java (the break keyword)
class BreakKeyword {
  public static void main( String args[ ] ) {
    int x = 10, y = 20;
    switch ( x+y ) {
      case 20:
        System.out.print( x );
        break;
      case 30:
        System.out.print( y );
      case 40:
        System.out.print( x+y );
        break;
      default:
        System.out.print( 50 );
    }
  }
}
Output:             Result:




      Nurse: “Doctor, the man you just treated collapsed on the front step. What should I do?”    
      Doctor: “Turn him around so it looks like he was just arriving.”