Switch Statement

A switch statement matches against multiple expressions and transfers control to a statement based on the given expression. Optionally a default case can be included which will be executed if no match is found.

switch(test-expression) {
    case expression-1:
        statements;
    case expression-2:
        statements;
    .
    .
    case expression-n:
        statements;
    default:
        statements;
}

Once it matches against the test expression, it will fall through the remaining cases till the end of switch including default. To prevent this fall through of one case to other case, we need use break keyword to exit out of the switch statement.

Below program, matches given operator with multiple operators, jumps directly to multiplication case and exits the case after executing it.

package com.techstackjournal;

public class SwitchExample1 {

	public static void main(String[] args) {
		int num1 = 10, num2 = 2;
		char operation = '*';

		switch (operation) {
		case '+':
			System.out.println(num1 + num2);
			break;
		case '-':
			System.out.println(num1 - num2);
			break;
		case '*':
			System.out.println(num1 * num2);
			break;
		case '/':
			System.out.println(num1 / num2);
			break;
		case '%':
			System.out.println(num1 % num2);
			break;
		default:
			System.out.println("Invalid operation");

		}

	}

}
20

In the test expression, you can include integer, char and String. We’ll learn about what is String later.

Sometimes, you may want to fall through other cases. In that case, you can remove break between cases. In the below program we want to match a character with vowels, if no match found it will run default case.

package com.techstackjournal;

public class SwitchExample2 {

	public static void main(String[] args) {
		char letter = 'e';

		switch (letter) {
		case 'a':
		case 'e':
		case 'i':
		case 'o':
		case 'u':
			System.out.println("It's a vowel");
			break;
		default:
			System.out.println("It's a consonant");

		}

	}

}
It's a vowel