How to understand Switch expressions in Java14
How to understand the Switch expression in Java14, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
Java 14 officially released the switch expression feature. In the previous two Java versions, the Java12,Java13,switch feature was just a preview.
The new switch expression helps avoid some bug because its expression and composition are easier to write.
Switch's new expression has two features:
Arrow expression return is supported.
Yied and return return values are supported.
Switch syntax switch (season) {before Java 14
Case SPRING:
Case AUTUMN:
System.out.println ("warm")
Break
Case SUMMER:
System.out.println ("hot")
Break
Case WINTER:
System.out.println ("cold")
Break
}
Java 14 switch expression switch (season) {
Case SPRING, AUTUMN-> System.out.println (warm)
Case SUMMER-> System.out.println (hot)
Case WINTER-> System.out.println ("cold")
}
When Java 14's switch expressions are expressed with arrows, we don't need to add break after every case to reduce our chances of making mistakes.
Before Java14, switch syntax returned the value String temperature = "".
Switch (season) {
Case SPRING:
Case AUTUMN:
Temperature = "warm"
Break
Case SUMMER:
Temperature = "hot"
Break
Case WINTER:
Temperature = "cold"
Break
Default:
Temperature = "hot and cold"
}
It does not support return values and needs to be returned through an intermediate variable.
The Java14 switch expression returns the value String temperature = switch (season) {
Case SPRING, AUTUMN-> "warm"
Case SUMMER-> "Hot"
Case WINTER-> "Cold"
}
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.