Two switch Statement Examples


Below give two code samples of switch statement.

SwitchStmt.java (the switch statement)
01class SwitchStmt {
02  public static void main( String args[ ] ) {
03    int x = 10, y = 20, z = 30;
04    switch ( 10+10 ) {
05      case x:
06        System.out.print( x );
07        break;
08      case y:
09        System.out.print( y );
10        break;
11      case z:
12        System.out.print( z );
13        break;
14      default:
15        System.out.print( 40 );
16        break;
17    }
18  }
19}
Output:             Result:

Another example of the switch statement is given next:

BreakKeyword.java (the break keyword)
01class BreakKeyword {
02  public static void main( String args[ ] ) {
03    int x = 10, y = 20;
04    switch ( x+y ) {
05      case 20:
06        System.out.print( x );
07        break;
08      case 30:
09        System.out.print( y );
10      case 40:
11        System.out.print( x+y );
12        break;
13      default:
14        System.out.print( 50 );
15    }
16  }
17}
Output:             Result: