0
0
Javaprogramming~5 mins

Switch statement in Java

Choose your learning style9 modes available
Introduction

A switch statement helps you choose between many options easily. It makes your code cleaner when you have to check one value against many cases.

When you want to run different code based on a day of the week.
When you need to perform actions depending on a menu choice.
When you want to handle different commands from a user input.
When you want to replace many if-else checks on one variable.
When you want your code to be easier to read and maintain.
Syntax
Java
switch (variable) {
    case value1:
        // code to run if variable == value1
        break;
    case value2:
        // code to run if variable == value2
        break;
    // more cases...
    default:
        // code to run if no case matches
        break;
}

The break statement stops the switch from running the next cases.

The default case runs if no other case matches. It is optional but useful.

Examples
This example prints the name of the day for the number 3.
Java
int day = 3;
switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    case 3:
        System.out.println("Wednesday");
        break;
    default:
        System.out.println("Other day");
        break;
}
This example shows how to group cases together to run the same code.
Java
char grade = 'B';
switch (grade) {
    case 'A':
        System.out.println("Excellent");
        break;
    case 'B':
    case 'C':
        System.out.println("Well done");
        break;
    case 'D':
        System.out.println("You passed");
        break;
    default:
        System.out.println("Try again");
        break;
}
Sample Program

This program uses a switch statement to find the name of the month from its number and prints it.

Java
public class SwitchExample {
    public static void main(String[] args) {
        int month = 4;
        String monthName;

        switch (month) {
            case 1:
                monthName = "January";
                break;
            case 2:
                monthName = "February";
                break;
            case 3:
                monthName = "March";
                break;
            case 4:
                monthName = "April";
                break;
            default:
                monthName = "Unknown";
                break;
        }

        System.out.println("Month number " + month + " is " + monthName);
    }
}
OutputSuccess
Important Notes

Always remember to use break to avoid running unwanted cases.

Switch works well with int, char, String, and enum types.

From Java 14+, you can use switch expressions for simpler code, but this example uses the classic form for beginners.

Summary

Switch helps pick one action from many based on a value.

Use case for each choice and break to stop.

default runs if no case matches.