Switch Statement
Java Switch Statement :
In Java, the switch statement is a control flow mechanism used to perform different actions based on the value of a variable or expression. It provides a concise way to evaluate a single variable against multiple values and execute different blocks of code based on the match found.
It's important to note that the switch statement works with char, byte, short, int, and their respective wrapper types (Character, Byte, Short, Integer). Starting from Java 7, it also supports String values.
The basic syntax of a switch statement in Java looks like this:
Here's a breakdown of how the switch statement works:
Switch Expression: The switch keyword starts the statement. It's followed by a pair of parentheses containing an expression or variable that you want to check against different values.
Case Labels: Inside the curly braces {}, you list different case labels. These represent specific values that the expression might match.
Match and Execute: When the value of the expression matches a case label, the code following that label is executed. It's like finding the right 'case' or platform to perform actions related to that particular value.
The 'Break' Statement: The break statement is used to exit the switch block after executing the code related to the matched case. It's like leaving the train station after reaching your intended platform. If break is omitted, the execution continues to the next case, which might not be what you want in every scenario.
No Match Found: If the expression doesn't match any case labels, the code in the default block (if it exists) is executed. It's like a safety net, catching any situation where the expression doesn't match any expected values.
The 'Default' Case: The default case is optional. It acts as a catch-all option. If no case matches the expression, the code in the default block is executed. It's like saying, "If nothing else fits, do this."
Here is an example to illustrate the usage of a switch statement in Java:
In this example, if day has a value of 3, the output will be: "The day is: Wednesday". If day does not match any of the case labels, the default case will assign the value "Weekend" to dayName.