Understanding switch Statement in Java


The switch statement allows you to select one of many code blocks to be executed based on the value of a variable.

Source Code

int day = 4;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    case 4:
        System.out.println("Thursday");
        break;
    default:
        System.out.println("Weekend");
}

Use switch for more readability when you have multiple conditions based on the same variable.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments