Skip to main content

Command Palette

Search for a command to run...

Switch Case - Java Programming

Published
View as Markdown
Switch Case - Java Programming
M

A Java Programmer with UI UX, DevOps, Front end, and Writing skills.

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.

More from this blog

Manju blogs

21 posts

I am a technology enthusiast. Learning is everything and directly proportional to your curiosity on the field makes you a master. Java | UX | front end | Cloud | with writing skills