0
0
JavaHow-ToBeginner · 3 min read

How to Use Switch Case in Java: Syntax and Examples

In Java, use the switch statement to select one of many code blocks to execute based on a variable's value. Each case defines a value to match, and break stops execution to prevent fall-through. The default case runs if no other case matches.
📐

Syntax

The switch statement evaluates an expression and executes the matching case block. Use break to exit the switch after a case runs. The default case is optional and runs if no other case matches.

  • switch(expression): The value to check.
  • case value: Code to run if expression equals value.
  • break; Stops further case checks.
  • default: Runs if no case matches.
java
switch (variable) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
    default:
        // default code block
        break;
}
💻

Example

This example shows how to use switch to print a message based on a day number.

java
public class SwitchExample {
    public static void main(String[] args) {
        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;
        }
    }
}
Output
Wednesday
⚠️

Common Pitfalls

Common mistakes include forgetting break statements, which causes "fall-through" where multiple cases run unintentionally. Also, the switch expression must be of a compatible type like int, String, or enum. Using unsupported types causes errors.

java
/* Wrong: Missing break causes fall-through */
switch (num) {
    case 1:
        System.out.println("One");
    case 2:
        System.out.println("Two");
        break;
}

/* Right: Break added to prevent fall-through */
switch (num) {
    case 1:
        System.out.println("One");
        break;
    case 2:
        System.out.println("Two");
        break;
}
📊

Quick Reference

  • Use switch for clear multi-choice branching.
  • Always add break unless intentional fall-through is needed.
  • default handles unmatched cases.
  • Supported types: int, char, String, enums.

Key Takeaways

Use switch to select code blocks based on a variable's value.
Always include break to avoid running multiple cases unintentionally.
The default case runs if no other case matches.
Switch supports types like int, String, and enums.
For clear code, use switch when you have many fixed options to check.