Friday 15 September 2017

Java Switch Statement

Cited from the Book Java How to Program

The switch multiple-selection statement performs different actions based on the possible values of a constant integral expression of type byte, short, int or char.

The switch’s controlling  expression compares this expression’s value (which must evaluate to an  integral value of type byte, char, short or int) with each case label. 

Listing cases consecutively in this manner with no statements between them enables the cases to perform the same set of statements.

For example,

        case 9:  // grade was between 90
         case 10: // and 100, inclusive
            ++aCount; // increment aCount
            break; // necessary to exit switch

The switch statement does not provide a mechanism for testing ranges of values, so every value you need to test must be listed in a separate case label. Each case can have multiple statements. The switch statement differs from other control statements in that it does not require braces around multiple statements in a case.

Without break statements, each time a match occurs in the switch, the statements for that case and subsequent cases execute until a break statement or the end of the switch is encountered. This is often referred to as “falling through” to the statements in subsequent cases.

The break statement is not required for the switch’s last case (or the optional default case, when it appears last), because execution continues with the next statement after the switch.

The expression in each case can also be a constant variable—a variable containing a value which does not change for the entire program. Such a variable is declared with keyword final. Java has a feature called enumerations. Enumeration constants can also be used in case labels.

As of Java SE 7, you can use Strings in a switch statement’s controlling expression and in case labels.

No comments:

Post a Comment