Title: Key Concept - Switch Statement
Course: CPS 189: Java Certification - Review, Practice & Prepare (Development) > Section: Learning Modules

Like the if statement, the switch statement also supports decision-making.

The switch statement functions similar to the if statement, but can be more readable when deciding among several blocks.

switch statement syntax:

switch (<switch-expression>)
{
case <case-expression-1>:
<block-1>;
break;
case <case-expression-2>:
<block-2>;
break;
...
case <case-expression-n>:
<block-n>;
break;
default:
<block-n>;
break;
}

- The <switch-expression> and <case-expression> must be the same data type.
- The expressions may be one of the following data types:
  - Primitive types: byte, short, char, or int
  - Enumerated
  - String
- The <switch-expression> is compared with each until:
  - A match is found
  - An optional default case is reached
  - The end of the switch statement
- If a match is found, then all statements following the matching <case-expression> are executed until:
  - An optional break statement is reached
  - The end of the switch statement

For additional study, view the resources under Level 1 Study Materials: Unit 2.