Java-Switch Statement

Switch Statement

The switch statement is provides a better alternative than a large series of if-else-if statements. Here is its general form:

The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal. Duplicate case values are not allowed. The switch statement is value of the expression is compared with each of the literal values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional. The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of “jumping out” of the switch.

Program

1

Program Source

class Javaapp {

    public static void main(String[] args) {
        
        int value = 4;
        switch(value){
            case 0:
                System.out.println("case 0");
                break;
            case 1:
                System.out.println("case 1");
                break;
            case 2:
                System.out.println("case 2");
                break;
            case 3:
                System.out.println("case 3");
                break;
            case 4:
                System.out.println("case 4");
                break;
            default:
                System.out.println("default");
                break;
        }
    }
}

Leave a Comment