MathBits.com
Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use  

The "switch" Statement

If your program must select from one of many different actions, the "switch" structure will be more efficient than an "if ..else..." structure.

switch (expression)
{
     case (expression 1):    {
                                            one or more Java statements;
                                            break;
                                            }
    case (expression 2):     {
                                           one or more Java statements;
                                           break;
                                           }
   case (expression 3):     {
                                          one or more Java statements;
                                          break;
                                          } 
                    . 
                    .
                    .

    default:                        {
                                        one or more Java statements;
                                        break;
                                        }
}


•  You MUST use a break statement after each "case" block to keep execution from "falling through" to the remaining case statements.

•  Only integer or character types may be used as control expressions in "switch" statements.

•  It is best to place the most often used choices first to facilitate faster execution.

•  While the "default" is not required, it is recommended.

If you need to have several choices give the same responses, you need to use the following coding style:

switch (value)
{
     case (1):
     case (2):
     case (3):   {
                       //The case code for 1, 2, 3
                       break;
                       }
     case (4):
     case (5):
     case (6):   {
                      //The case code for 4, 5, 6
                      break;
                      }
     default:    {
                     //The code for other values
                     break;
                      }
}

 

                                                                   


Return to Unit Menu | Java Main Page | MathBits.com | Terms of Use