Switch statement in Java

The ‘switch’ statement is used to execute a block of code from different number of cases. The expression of the switch statement is compared with the cases and if there is a match the code of that block is executed.

Break statement is used to break the execution of further cases. If no cases is matched then default statement is executed. The following program shows the use of switch- case statement.

package com.company;

public class SwitchStatement {

    public static void main(String[] args) {
        int number = 5;

        switch (number) {

            case 1:
                System.out.println("The number is 1");
                break;

            case 2:
                System.out.println("The number is 2");
                break;

            case 3:
                System.out.println("The number is 3");
                break;

            case 4:
                System.out.println("The number is 4");
                break;

            case 5:
                System.out.println("The number is 5");
                break;

            case 6:
                System.out.println("The number is 6");
                break;

            case 7:
                System.out.println("The number is 7");
                break;

            default:
                System.out.println("The number is null");
        }
    }
}

Output:

The number is 5

The following program makes the the use of default statement. Here the number is 9 and there is no cases matched, so default statement is executed.

package com.company;

public class SwitchStatement {

    public static void main(String[] args) {
        int number = 9;

        switch (number) {

            case 1:
                System.out.println("The number is 1");
                break;

            case 2:
                System.out.println("The number is 2");
                break;

            case 3:
                System.out.println("The number is 3");
                break;

            case 4:
                System.out.println("The number is 4");
                break;

            case 5:
                System.out.println("The number is 5");
                break;

            case 6:
                System.out.println("The number is 6");
                break;

            case 7:
                System.out.println("The number is 7");
                break;

            default:
                System.out.println("The number is null");
        }
    }
}

Output:

The number is null
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments