← Back to Chapters

Java Switch Statement

? Java Switch Statement

? Quick Overview

The switch statement in Java is a control flow statement that allows you to execute different blocks of code based on the value of a variable or expression. It is often used as a cleaner and more readable alternative to multiple if-else conditions.

? Key Concepts

  • Evaluates a single expression once
  • Matches the expression value with case labels
  • Uses break to stop execution
  • default runs when no case matches
  • Supports int, char, String, and enum

? Syntax / Theory

? View Code Example
// General syntax of Java switch statement
switch(expression) {
case value1:
    statements;
    break;
case value2:
    statements;
    break;
default:
    statements;
}

? Code Example

? View Code Example
// Java program demonstrating switch statement
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;
case 4:
    System.out.println("Thursday");
    break;
default:
    System.out.println("Invalid day");
}

? Live Output / Explanation

The value of day is 3, so the control jumps to case 3 and prints Wednesday. The break statement stops further execution.

✅ Tips & Best Practices

  • Always use break to avoid fall-through
  • Use default to handle unexpected values
  • Prefer switch when checking one variable against many values
  • Use enhanced switch (Java 14+) for cleaner code

? Try It Yourself

  • Create a switch program for month names
  • Use String values inside a switch
  • Remove break and observe fall-through behavior
  • Rewrite an if-else ladder using switch