SCJP Study Guide:
Flow Control


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Java: switch Statement - Overview

The 'switch' Statement


Purpose


Use the switch statement to conditionally perform statements based on an integer expression or enumerated type. The switch statement allows you to choose from many statements based on an integer (including char) or enum value.

Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use based on readability and other factors. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or enumerated value.


Syntax


switch (expression) {
  case constant1:
        statements // do these if expression == constant1
        break;
  case constant2: 
        statements // do these if expression == constant2
        break;
  case constant2:
  case constant3:
  case constant4:         //  Cases can simply fall thru.
        statements // do these if expression ==  any of constant(2,3,4)
        break;
  . . .
  default:
        statements // do these if expression != any above
}

The switch statement executes the case corresponding to the value of the expression. Normally the code in a case clause ends with a break statement, which exits the switch statement and continues with the statement following the switch. If there is no corresponding case value, the default clause is executed. If no case matched and there is no default clause, execution continues after the end of the switch statement.


Notes


 

The switch expression must be of type byte, short, int,  char, or enumerated type; each of the values specified in the case statements must be of a type compatible with or assignable to the expression.

Each case value must be a constant expression that can be evaluated at compile time, not a variable. Duplicate case values are not allowed.

Compiler checks each case value against the range of the switch expression?s data type. The following code won?t compile.

byte b;

switch (b) {

   case 200: // 200 not in range of byte

   default:

}

If no case value matches the switch expression value, execution continues at the default clause. This is the equivalent of the "else" for the switch statement.

The default clause can be placed anywhere. It?ll be executed only if none of the case values match. It is written after the last case be convention, and typically isn't followed by break because execution just continues out the bottom of switch if this is the last clause. If you place it in the top or middle, you need to add break statement.

The break statement causes execution to exit to the statement after the end of the switch. This has the effect of jumping out of the switch.

The break statement is optional. If it is omitted, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them.

Empty switch construct is a valid construct. But any statement within the switch block should come under a case label or the default case label.

The default clause is optioanl. Always include a default clause in your switch statement as a general policy of defensive programming - assume there will be bugs in your code and make sure they are caught.

The switch can be nested. Nested case labels are independent, don?t clash with outer case labels.


Examples


public class SwitchEnumDemo {
    public enum Month { JANUARY, FEBRUARY, MARCH, APRIL,
                        MAY, JUNE, JULY, AUGUST, SEPTEMBER,
                        OCTOBER, NOVEMBER, DECEMBER }

    public static void main(String[] args) {
        Month month = Month.FEBRUARY;
        int year = 2000;
        int numDays = 0;

        switch (month) {
            case JANUARY:
            case MARCH:
            case MAY:
            case JULY:
            case AUGUST:
            case OCTOBER:
            case DECEMBER:
                numDays = 31;
                break;
            case APRIL:
            case JUNE:
            case SEPTEMBER:
            case NOVEMBER:
                numDays = 30;
                break;
            case FEBRUARY:
                if ( ((year % 4 == 0) && !(year % 100 == 0))
                     || (year % 400 == 0) )
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                numDays=0;
                break;
        }
        System.out.println("Number of Days = " + numDays);
    }
}

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |