Switch case

Published: (February 7, 2026 at 04:44 AM EST)
2 min read
Source: Dev.to

Source: Dev.to

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 cleaner and easier to read than writing many if–else statements.
  • In Java, the switch statement works with primitive types int, byte, short, char and, since Java 8, with String.
  • Starting with Java 12, the arrow syntax (->) can be used as a more concise alternative to break.

Syntax

switch (expression) {
    case value1:
        // statements
        break;               // stops fall‑through
    case value2 ->          // arrow syntax (Java 12+)
        // statements
    default:
        // default statements
}
  • break; stops execution after the matched case block.
  • Arrow syntax (->) automatically prevents fall‑through, so an explicit break is not needed.

Example 1 – Switching on an int

public class SwitchCaseExample {
    public static void main(String[] args) {
        int day = 5;   // can be int, byte, short, or char

        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("Holiday");
        }
    }
}

Example 2 – Switching on a String (Java 8+)

package moduleTwo;

public class SwitchCaseTest {
    public static void main(String[] args) {
        String say = "hello";

        switch (say) {
            case "hi":
                System.out.println("hey");
                break;
            case "hello":
                System.out.println("Good morning");
                break;
            default:
                System.out.println("unknown");
        }
    }
}

Example 3 – Multiple Labels and Arrow Syntax (Java 12+)

public class SwitchCaseTest {
    public static void main(String[] args) {
        String grade = "B";

        switch (grade) {
            case "A", "B" -> System.out.println("pass");
            case "C"       -> System.out.println("fail");
            default        -> System.out.println("no result");
        }
    }
}
0 views
Back to Blog

Related posts

Read more »

Constructor in java

What is Constructors? A constructor is a special method in Java that is automatically executed when an object of a class is created. It is mainly used to initi...

Data Types in Java

Data types specify the different sizes and values that can be stored in a variable. Java is a statically‑typed language, so every variable must be declared with...

Exception Handling in Java

Introduction Java exceptions are objects that represent errors or unusual conditions that occur during runtime. They disrupt the normal flow of a program, and...