Switch Case

The switch statement in Java is a control flow statement used to execute one block of code among many based on the value of a variable or expression. It provides a cleaner and more readable alternative to using multiple if-else statements, especially when dealing with a large number of conditions.

  • Expression Evaluation: The switch expression is evaluated.
  • Case Matching: The value is compared with the case labels in the order they are defined.
  • Execution: When a match is found, the statements in the corresponding case are executed.
  • Break Statement: After executing the case block, the break statement exits the switch to prevent “fall-through.”
  • Default Case: If no match is found, the default block executes (optional).

Syntax

  • The expression in a switch must evaluate to a value of types like int, char, String, or enums.
  • The break statement is necessary to prevent execution from “falling through” to subsequent cases.
  • The default case is optional but useful for handling unexpected values.
  • Duplicate case values are not allowed.

Example

  • Input Value: The day variable holds the value 5.
  • Switch Execution:
    • The switch statement evaluates the day variable.
    • It matches 5 with the case 5: label.
    • The code inside case 5: executes: System.out.println("Friday");.
  • Break: The break statement prevents the execution from falling into subsequent cases.

Output

Advanced Usage

From Java 12 onward, the switch statement introduced an enhanced syntax called “switch expressions,” which simplifies the flow and allows returning a value directly.

Example

Output