Java by Example: Switch

Switch statements in Java are multi-way branches that enable an expression to be tested for equality against a list of values. Each value is a case, and the variable being switched on is checked for each case.

public class Main {
public static void main(String[] args) {

Here's a basic switch in Java.

    int i = 2;
    switch (i) {
        case 1:
            System.out.println("one");
            break;
        case 2:
            System.out.println("two");
            break;
        case 3:
            System.out.println("three");
            break;
        default:
            System.out.println("other");
            break
          

The variable i is being switched upon. It is compared with each case. If a match is found, the statements after the matching case are executed. If no match is found, the default case is executed.

The break keyword at the end of each case block is necessary to prevent "fallthrough", where after a match is found, the code would continue executing the statements in the following case blocks as well. If the break keyword is omitted, ensure that is the desired behavior.

}
}

← Java by Example