New Switch Statement in Java
How you write switch statement in Java (Old way)?
To write a switch statement in Java, you follow a specific
syntax. The switch statement allows you to evaluate the value of an expression
against multiple case values and execute the corresponding block of code based
on the matched case. Here's the basic structure of a switch statement in Java:
Explanation:
- The expression is the value that you want to evaluate and compare with the cases.
It must be of a primitive type (e.g., int, char) or an enumerated type (enum) in
Java 7 and later.
- Each case represents a specific value that you want to compare with the expression. If the expression matches a case value, the corresponding block of code
under that case will be executed.
- After
executing the code inside the matching case, the break statement is used to exit the switch block. If you omit the break, the code will fall through to the next case, executing its code
as well. This behavior is useful in some cases but should be used with
caution.
- You
can have multiple case blocks with different values, allowing
you to handle various scenarios based on the expression.
- The default case is optional and is used when none of the case values match the expression. It
provides a default block of code to be executed in such cases.
Example:
What is the new Switch statement in Java?
In September 2021, Java 12 introduced a new preview feature
called "Switch Expressions," which provides a more concise and
flexible way of writing switch statements. This feature was later finalized and
became a standard feature in Java 14.
Switch expressions allow you to use the switch
statement as an expression rather than just a statement. The syntax for switch expressions is different from the traditional switch statements. Here's how you write a switch expression in Java:
Explanation:
The switch keyword is followed by the expression that you want to evaluate, just like in traditional switch statements.
Instead of using the case keyword, you use the -> symbol to specify the value and the corresponding expression or result that should be returned when the expression matches the case.
You can have multiple cases separated by ->, and each case can have its own expression or value to be returned.
The default case is specified using default
-> and provides a result when none
of the cases match the expression.
Example:
In this example, the switch expression is used to assign the dayName
variable based on the
value of the dayOfWeek
variable. The output
will be "The day is: Tuesday" since dayOfWeek
is set to 3.
Please note that switch expressions were introduced as a preview feature in Java 12 and became a standard feature starting from Java 14. As Java continues to evolve, newer versions may introduce further enhancements or changes to the switch expressions.
Here is the screenshot of output from IntelliJ IDE:
Comments
Post a Comment