Switch Statement

A switch statement considers a value and compares against several possible matching labels(patterns). It then executes an appropriate block of code, based on the first pattern that matches successfully.

A switch statement provides an alternative to the if statement for responding to multiple potential states.

Syntax

switch (some value to consider) {
case value 1:
respond to value 1
break;
case value 2:
respond to value 2
break;
default:
otherwise, do something else
break;
}


The body of each switch case is a separate branch of code execution, in a similar manner to the branches of the if statement. The switch statement determines which branch should be selected. This is known as switching to the value that is being considered.

Example Switch

Every switch statement must be exhaustive. That is, every possible value being considered must be matched by one of the switch cases.

char character = 'o';

switch (character) {
case 'a':
//Print its a vowel
break;
case 'e':
//Print its a vowel
break;
case 'i':
//Print its a vowel
break;
case 'o':
//Print its a vowel
break;
case 'u':
//Print its a vowel
break;
default:
//Print its not a vowel
break;
}


Fall Through in Case Statement

You can match multiple cases by skipping the break keyword.

char character = 'o';

switch (character) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
//Matched either a, e, i, o, u
break;
default:
//Print its not a vowel
break;
}