3.6 Switch Statement

Switch statement give us the power to choose one option among many alternatives.

A switch statement executes according to the following rules:

As illustrated in following code segment. When the value of the expression (day) is matched against a case value (1,2,..) , the statements execute until a break statement is found. A break statement causes an immediate exit from the switch structure. If the value of the expression does not match any of the case values, the statements following the default label execute.

import java.util.Scanner; // Needed for the Scanner class

/**
 *  This program demonstrates switch statement.
 */
public class WeekDay
{
   public static void main(String[] args)
   {
      int day;    // to hold day value

      // Create a Scanner object for keyboard input.
      Scanner console = new Scanner(System.in);

      // Get day.
      System.out.print("Enter number 1-7 : ");
      day = console.nextInt();

      // Determine the corresponding week's day
      switch (day)
      {
      case 1 :
         System.out.println("Sunday");

         break;

      case 2 :
         System.out.println("Monday");

         break;

      case 3 :
         System.out.println("Tuesday");

         break;

      case 4 :
         System.out.println("Wednesday");

         break;

      case 5 :
         System.out.println("Thursday");

         break;

      case 6 :
         System.out.println("Friday");

         break;

      case 7 :
         System.out.println("Saturday");

         break;

      default :
         System.out.println("Invalid input");
      }
   }
}          

Output 1:
Enter number 1-7 : 3
Tuesday

Output 2:
Enter number 1-7 : 9
Invalid input

 

Here is another example of switch statements. The following program asks the user to input choice in y/n and display the output according to value input by user :

import java.util.Scanner;    // Needed for the Scanner class

/**
 * This program demonstrates the switch statement.
 */
public class SwitchDemo
{
   public static void main(String[] args)
   {
      char choice;    // To store the user's choice

      // Create a Scanner object to read input.
      Scanner console = new Scanner(System.in);

      // Ask the user to enter y or n.
      System.out.print("Enter Y or N: ");
      choice = console.next().charAt(0);

      // Determine which character the user entered.
      switch (choice)
      {
      case 'Y' :
      case 'y' :
         System.out.println("You entered Y.");

         break;

      case 'N' :
      case 'n' :
         System.out.println("You entered N.");

         break;

      default :
         System.out.println("Incorrect Input!");
      }
   }
}