Java Switch Statement
✓ The switch statement in Java is a control flow statement that allows the execution
of one block of code among multiple alternatives.
✓ It provides a more readable and efficient way of writing a series of if-
else statements when comparing the same expression against different values.
✓ Usage
✓ The switch statement evaluates an expression, matches the expression's value
against a series of case labels, and executes the block of code associated with the
matching case.
✓ If no case matches, the default block is executed, if it is present.
• expression: A variable or expression that is evaluated once.
• value1, value2, ...: Constant expressions that the expression is compared
against.
• break: Terminates the switch block. Without it, execution falls through to
subsequent cases.
• default: Optional block executed if no case matches.
• Example 1: Basic switch Statement
✓ In this example, the switch statement evaluates the variable number.
Since number equals 2, the output will be "Two".
✓ The break statement prevents fall-through to subsequent cases.
Example 2: switch with Strings
✓ This example demonstrates the use of a switch statement with a String.
The switch checks the value of fruit, and since it is "Apple", the output will be
"Fruit is Apple".
Example 3: switch without break
✓ In this example, multiple case labels are used to execute the same block of code.
✓ The output will be "Weekday" because day is 3, and the break statement prevents
execution from falling through to the "Weekend" cases.
Tips and Best Practices
• Use break Statements: Always include break statements unless intentional fall-
through is desired. This prevents unintended execution of subsequent cases.
• Default Case: Include a default case to handle unexpected values and improve
code robustness.
• Expression Types: The switch expression can be of
type byte, short, int, char, String, or an Enum.
• Avoid Complex Logic: Use switch for simple scenarios with discrete values. For
complex conditions, consider using if-else statements.
• Java 12+ Enhancements: In Java 12 and later, switch expressions allow
returning values and using the yield keyword for more concise code.