Switch Case

Published: (February 3, 2026 at 11:37 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

What is a switch statement?

The switch keyword in Java is used to execute one block of code among many alternatives. The expression is evaluated once and compared with the values of each case. If the expression matches a case value, the code for that case is executed. If there is no match, the code of the default case is executed.

Syntax

switch (expression) {
    case value1:
        // statements
        break; // optional
    case value2:
        // statements
        break;
    // ...
    default:
        // statements
}
  • The break statement terminates the switchcase statement.
  • If break is omitted, execution falls through to subsequent cases.

Allowed types for the expression

  • byte
  • short
  • int
  • char
  • String (since Java 7)

Types not allowed

  • long
  • float
  • double
  • boolean

Default case

The default case is optional. It is used to handle unexpected values when none of the specified cases match.

Example

public class SwitchExample {
    public static main(String[] args) {
        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;
            case 'F':
                System.out.println("Better try again");
                break;
            default:
                System.out.println("Invalid grade");
        }
    }
}

Switch expression syntax in Java 12 and above

Java 12 introduced the arrow (->) syntax for switch expressions, which eliminates the need for explicit break statements.

Example (Java 12)

int day = 1;
switch (day) {
    case 1, 7 -> System.out.println("Weekend");
    case 2, 3, 4, 5, 6 -> System.out.println("Weekday");
    default -> System.out.println("Invalid day");
}
Back to Blog

Related posts

Read more »

Operators

What are Operators in Java? Operators are symbols used to perform operations on variables and values. Types of Operators in Java - Arithmetic Operators - Assig...

Introduction to Java

!Cover image for Introduction to Javahttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s...

Java Notes

Running Java from Terminal bash javac App.java && java App javac compiles the Java source file App.java into bytecode App.class. The && operator runs the secon...