Switch Case - Java Programming

Switch Case - Java Programming

Introduction

Switch case statements are a way to choose from a list of options based on the value of a variable. In Java, you can use a switch case statement to test a variable against a list of possible values and perform a different action for each value. Here's an example:

public static void main(String[] args) {
    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;
        case 5:
            System.out.println("Friday");
            break;
        default:
            System.out.println("Weekend");
    }
}

In this example, the switch statement is testing the value of the variable day against a list of possible values (1, 2, 3, 4, and 5). If the value of the day is 1, then the program will print "Monday". If the value of day is 2, then the program will print "Tuesday", and so on. The break statement is used to exit the switch statement after the appropriate action has been taken.

The default case is used to handle any values that are not covered by the other cases. In this example, if the value of the day is not 1, 2, 3, 4, or 5, then the program will print "Weekend"

I hope this helps you understand how switch case statements work in Java programming. And, in the next Java tutorial, we will be going over the methods. This is considered one of the most basic, easy, and important topics to learn OOPs and other OOP-related topics quickly.

Did you find this article valuable?

Support Manjunath Irukulla by becoming a sponsor. Any amount is appreciated!