switch case

Definition

The switch case statement is used to select one of many blocks of code to be executed.

It is an alternative way to create a multiway branch (instead of using if else).

Syntax

switch case

A simple switch case statement has the following syntax:

switch (expression) {
    case value1:
        // code to execute if expression matches value1
        break;	// optional	break
    case value2:
        // code to execute if expression matches value2
        break;	// optional	break
    ......
    default:	// optional default
        // code to be executed if the all cases are not matched
}
switch (expression) {
    case value1:
        // code to execute if expression matches value1
        break;	// optional	break
    case value2:
        // code to execute if expression matches value2
        break;	// optional	break
    ......
    default:	// optional default
        // code to be executed if the cases are not matched
}

JavaScript and Java syntax.

Example - A Simple Menu

We will create a menu and use the switch case to check if a user enters 'a' to add, 's' to subtract or 'q' to Quit.

JavaScript and Java example.

  1. We assign 's' to the variable option and check if this matches one of the cases. We will also test how the switch runs when the break keyword is not included.
  2. var option = 's'; 
    
    switch (option) {
        case 'a':
            alert("Add selected");
        case 's':
            alert("Subtract selected");
        case 'q':
            alert("Quit selected");		  
        default:	
            alert("Incorrect input");
    }
    char option = 's';  
     	
    switch (option) {
        case 'a':
            System.out.println("Add selected");
        case 's':
            System.out.println("Subtract selected");
        case 'q':
            System.out.println("Quit selected");	  
        default:	
             System.out.println("Incorrect input");
    }

    When run, the value in option matches the 's' of the second case and executes the associated code to display the message 'Subtract selected.'

    However, when a match is found, any remaining code in the switch will be executed until either a break is found or the end of the switch is reached. Even although the option value does not match the remaining cases, the following is displayed: 'Subtract selected', 'Quit selected', 'Incorrect input'.

    There might be occasions when you want this type of logic in your program, but this example requires only the matched code to run.

  1. Now we will add the break keyword so that only the code associated with the matching case will be executed. We will also ensure that our program deals with any upper case characters.
  2. var option = 'S'; 
    option = option.toLowerCase();
    
    switch (option) {   
        case 'a':
            alert("Add selected");
            break;	
        case 's':
            alert("Subtract selected");
            break;	
        case 'q':
            alert("Quit selected");
            break;		  
        default:	
            alert("Incorrect input");
    }
    char option = "S";
    option = Character.toLowerCase(option);
    
    switch (option) {
        case 'a':
            System.out.println("Add selected");
            break;	
        case 's':
            System.out.println("Subtract selected");
            break;	
        case 'q':
            System.out.println("Quit selected");
            break;	  
        default:	
             System.out.println("Incorrect input");
    }

    As each case value is in lower case, the input value is converted to lower case prior to testing for a match in the switch case.

    If a case match is found, the associated code block is executed. Any further code in the following cases is ignored as the keyword break is used.

    The code specified within the default will be run if the users input does not match one of the case values. A break is not required within the default block as it is the last block of the switch.

  1. We will now get the input from the user and store it in the option variable. We will also store the outcome of the switch case match in a variable selection to be used later in the program.
  2. var option, selection; 
    option = prompt("Enter 'a' to Add, 's' to Subtract, 'q' to Quit");
    option = option.toLowerCase();
    
    switch (option) {
        case 'a':
            selection = "Add";
            break;	
        case 's':
            selection = "Subtract";
            break;	
        case 'q':
            selection = "Quit";
            break;		  
        default:	
            selection = "Incorrect input";
    }
    document.write(selection);
    
    char option;
    String selection;
      
    Scanner input = new Scanner(System.in);
      
    System.out.println("Enter 'a' to Add, 's' to Subtract, 'q' to Quit");
    option = input.next().charAt(0); 
    option = Character.toLowerCase(option);
    
    switch (option) {
        case 'a':
            selection = "Add";
            break;	
        case 's':
            selection = "Subtract";
            break;	
        case 'q':
            selection = "Quit";
            break;	  
        default:	
            selection = "Incorrect input";
    }
    System.out.println(selection);
    

    The examples now get input from the user and save the input into the variable option.

    We store the result of the switch case into the variable selection and display this at the end of the code.


To get a good understanding of the logic developed here and the switch case structure, view this in the Code Visualiser , or play with the code below (press the "Run Code" button to run the code): JS Bin on jsbin.com .