From the course: Nail Your Java Interview

Unlock the full course today

Join today to access over 22,500 courses taught by industry experts or purchase this course individually.

Leverage new switch expressions

Leverage new switch expressions - Java Tutorial

From the course: Nail Your Java Interview

Start my 1-month free trial

Leverage new switch expressions

- [Instructor] In newer versions of Java, switch expressions have been enhanced to allow you to set a value directly to a variable. This is an example of a switch statement we're used to. We use the stage variable to determine the value of the string season. If stage is 0, the season is Spring, if stage is 1, the season is Summer, and so on. At the end, we print the value of the season string. It's quite a bit of code to do a simple operation, but with the additions from Java 12 and Java 14, we can simplify this switch statement. We'll still have our int stage 2, but we're able to declare and initialize our season string with our switch statement. Here, we write String season, and it will have the value of what our switch statement returns. For the switch statement, we have our cases. Case 0 maps to Spring, case 1 maps to Summer, and so on. For the default case, we have an invalid stage. Once the season is set, we print…

Contents