Switch Statement

Optional Node
Premium Content - Free Preview

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.


End of Free Content Preview. Please Sign in or Sign up to buy premium content.

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]