SE-1020 Dr. Mark L. Hornick 1 The switch statement int gradeLevel = kbd.nextInt(); // can be byte or short also, but not long switch( gradeLevel ) { // examine value of gradeLevel case 1 : System.out.print("Go to the Gymnasium"); break; case 2 : System.out.print("Go to the Science Auditorium"); break; case 3 : System.out.print("Go to Harris Hall Rm A3"); break; case 4 : System.out.print("Go to Bolt Hall Rm 101"); break; } This statement is executed if the gradeLevel is equal to 1. This statement is executed if the gradeLevel is equal to 4.
SE-1010 Dr. Mark L. Hornick 2 The switch statement consists of a switch control expression and one or more case statements switch ( gradeLevel ) { case 1: System.out.print( "Go to the Gymnasium" ); break; case 2: System.out.print( "Go to the Science Auditorium" ); break; case 3: System.out.print( "Go to Harris Hall Rm A3" ); break; case 4: System.out.print( "Go to Bolt Hall Rm 101" ); break; } Case Body The Switch expression is an arithmetic expression that evaluates to an integer value Case Label Colon
SE-1010 Dr. Mark L. Hornick 3 The break statements cause the switch to terminate switch ( N ) { case 1: x = 10; break; case 2: x = 20; break; case 3: x = 30; break; } x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? false true break;
SE-1010 Dr. Mark L. Hornick 4 A switch without break statements will not terminate after the case is handled switch ( N ) { case 1: x = 10; case 2: x = 20; case 3: x = 30; } x = 10; false true N == 1 ? x = 20; x = 30; N == 2 ? N == 3 ? false true The flow will first start from the matching case body and then proceed to the subsequent case bodies.
SE-1010 Dr. Mark L. Hornick 5 the default block handles cases not explicitly handled switch (ranking) { case 10: case 9: case 8: System.out.print("Master"); break; case 7: case 6: System.out.print("Journeyman"); break; case 5: case 4: System.out.print("Apprentice"); break; default: System.out.print("Input error: Invalid Data"); break; }
SE-1010 Dr. Mark L. Hornick 6 The switch expression can also be a char datatype switch ( ranking ) { case ‘a’: System.out.print( "Go to the Gymnasium" ); break; case ‘b’: System.out.print( "Go to the Science Auditorium" ); break; case ‘c’: System.out.print( "Go to Harris Hall Rm A3" ); break; case ‘d’: System.out.print( "Go to Bolt Hall Rm 101" ); break; } The variable ranking is a char datatype