Switch Statement

Optional Node
Collapse Content

If you want to run a block of code if a condition is true, you can use an if statement. If you want to run different code for multiple conditions, you can use multiple else if statements. In the last node, the Java Help Menu printed a different statement for different values of the selection variable:

    if(selection == 1){
        System.out.println("for(initialization; condition; iteration){ statment; }");
    }
    else if(selection == 2){
        System.out.println("while(condition){ statement; }");
    }
    else if(selection == 3){
        System.out.println("do{ statement; } while(condition);");
    }

switch statement
Each if statement just checked if selection equaled different values. To avoid repeating variable equality expressions, Java has another control structure for cases like these: the switch statement. Its general common form looks like this:

switch (variable) {
   case value1:
      statements1
      break;
   case value2:
      statements2
      break;

    // (more cases) ...

   default:  // optional default case
      statementDefault
} 

// switch statement over and code continues...

The previous menu code could be improved with the switch statement:

 switch (selection){
            case 1:
                System.out.println("for(initialization; condition; iteration){ statement; }");
                break;
             case 2:
                System.out.println("while(condition){ statement; }");
                break;
            case 3:
                System.out.println("do{ statement; } while(condition);");
                break;
        }

This code is similar to the else-if statements, but slightly clearer and more optimized. Java will look at the value of the selection variable and then jump to the case that matches its value.

break
Note that it says break; after each case. It's important to remember this, since otherwise Java will continue on to the next case (despite the variable being different than the next case). Without the break statements above, if selection was 2, the program would execute both case 2 and case 3.

switch-statement-diagram

The break statements prevent the code execution from falling through, so it just executes the selected case:
switch-break-statement-diagram

On rare occasions however, you may choose to leave out some break statements so multiple cases get executed.

details
The switch statement can be used to replace multiple else if statements that check if a single variable equals different values. The variable needs to be of type int, char or (as of Java 7) String.* Each case needs to have its own unique value. You can optionally have a default case at the end which will run if the switch variable does not match any of the case values. This is like the else statement at the end of an if - else if block.

* It can also be of type short, byte and enum, but you don't need to worry about that now.

Challenge

Given the number of a day in the week (as an integer from 1 to 7), print the day's name in English. For example, if given 2, print Monday. If the number is not from 1 to 7, print "Not a day" instead.

Please sign in or sign up to submit answers.

Alternatively, you can try out Learneroo before signing up.

Comments

  • my code
    hey. im need help.. im didnt understand

  • Look at the general syntax of the switch statement. Here's one with only one case, which will print "word" when num is 1:

    switch (num) {
       case 1:
    
    cont...
  • Here is my code:

Contact Us
Sign in or email us at [email protected]