/* * ==================================================================================== * DemoSwitch.java: The switch (or case) statement provides a mechanism for determining * which statements are to be executed depending on a variable's value matching a label. * The body of switch statement is known as a switch block. * * -- Any statement immediately contained by the switch block may be labeled * with one or more case or default labels. * -- The switch statement evaluates its expression and executes the * appropriate case. * -- default is used for the else situation. * * Note. In the early version of Java the selection variable could only be int or * char datatype. Now it can also be an enum type (see the section on enumerated * types for an example. * * Written By: Mark Austin October 2008 * ==================================================================================== */ public class DemoSwitch { public static void main ( String [] args ) { // Part 1: Set an int variable value .... int i = 1; switch (i) { case 1: System.out.println("You typed a 1"); break; case 2: System.out.println("You typed a 2"); break; default: System.out.println("That was an invalid entry."); }; // Part 2: Set a char value .... char cA = 'A'; switch ( cA ) { case 'A': System.out.println("You selected the letter A"); break; case 'B': System.out.println("You selected the letter B"); break; default: System.out.println("That was an invalid entry."); }; // Part 3: Case statements can be bundled into groups ... char cB = 'a'; switch ( cB ) { case 'A': case 'B': System.out.println("You selected an UPPER CASE letter"); break; case 'a': case 'b': System.out.println("You selected a LOWER CASE letter"); break; default: System.out.println("That was an invalid entry."); }; // Part 4: A common programming mistake is to accidently leave out a // break statement. Instead of leaving the switch statement // the program control falls into the next case. System.out.println(); System.out.println("Simulate a missing break in the switch statement"); char cC = 'B'; switch ( cC ) { case 'A': case 'B': System.out.println("You selected an UPPER CASE letter"); case 'a': case 'b': System.out.println("You selected a LOWER CASE letter"); break; default: System.out.println("That was an invalid entry."); }; } }