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 »

제어 함수

조건문 Conditional Statement 조건에 따라 특정 동작을 하도록 하는 프로그래밍 명령어 명제 - 참 또는 거짓을 객관적이고 명확하게 판별할 수 있는 문장이나 식 관계 연산자 - x == y - x != y 논리 연산자 - X and Y - X or Y - not X IF...

Switch case

Overview - A switch case is a control statement that lets you run different blocks of code based on the value of a variable or expression. - It is often cleane...