In this article, we will understand the concept of switch expressions introduced in java 12 and modified in java 13 and 14.
Switch expression is a new feature that was added in java 12 to address some problems in traditional switch statement.
If you are not familiar with switch statement, then go through this article.
First, we shall look at the problems in the traditional switch and how switch expression addresses the solution to these.
1. Multiple break statements
Traditional switch, also referred as switch statement, requires break statement after every case block as shown highlighted below.
int num = 2; switch(num) { case 1: // code break; case 2: // code break; case 3: // code break; case 4: // code break; }
If any break
is accidentally missed, leads to unexpected errors and fall through(meaning that a case block below the matched case executes).
2. Repeated variable initialization
Conside the below switch statement
String size = "S"; int price = 0; switch(size) { case "S": case "M": price = 500; break; case "L": case "XL": price = 700; break; case "XXXL": price = 1000; break; }
Each case block in the above switch statement initializes/modifies the value of a variable and the variable needs to be written again and again.
It would be better if the case block would be able to assign this value directly to the variable without writing it again and again.
3. Repetition of case statement
If a single case statment should match multiple values, then it needs to be repeated for each label as shown in the previous example.
Switch expression is a new form of traditional switch statement where case statements are followed by an arrow instead of a colon as shown below.
switch(variable) { case label1 -> {} case label2 -> {} }
Such case labels are also called arrow labels.
Further, multiple case labels can be written separated by a comma without repetition of case
keyword as below.
switch(variable) { case label1, label2, label3 -> {} case label4 -> {} }
Switch expression example
Below is an example of a simple switch expression.
String size = "S"; switch (size) { case "S", "M" -> System.out.println("Price is 500"); case "L", "XL" -> System.out.println("Price is 700"); case "XXXL" -> System.out.println("Price is 1000"); }
Look, how cleaner it looks.
Note that there is no break statement after each case block.
If any case block has multiple statements, then they should be enclosed between curly braces.
Switch expression will execute a case block only when its label matches the switch variable. There is no fall through, that is, case statements after the match case will not be executed.
A switch expression can also return a value to the calling code directly without the need of creating an extra variable.
Look at the following example
String size = "S"; int price = switch (size) { case "S", "M" -> 500; case "L", "XL" -> 700; case "XXXL" -> 1000; default -> -1; }; System.out.println("Price is " + price);
In this example, switch expression returns an integer value and assigns it to a variable.
For returning a value from a switch expression, remember following pointers
1. case block can directly write the value to be returned after the arrow, no need of any return
statement.
2. A default
case is mandatory if the switch expression returns a value.
3. Result of the switch expression should be assigned to a variable or preceded with a return
statement or enclosed between a print statement.
That is, there should be something that consumes the value returned by the expression.
4. If a case block consists of multiple statements, then you cannot return a value straight away. Thus, below code is not allowed
String size = "S"; int price = switch (size) { case "S", "M" -> { // some code 500; } case "L", "XL" -> 700; case "XXXL" -> 1000; default -> -1; }; System.out.println("Price is " + price);
When the switch expression is returning a value, do not forget to end it with a semi-colon.
yield statement
In such a scenario, where a case block needs to return a value and it contains multiple statements, the value can be returned using yield
statement followed by the value.
Thus, above example can be written as
String size = "S"; int price = switch (size) { case "S", "M" -> { // some code yield 500; } case "L", "XL" -> 700; case "XXXL" -> 1000; default -> -1; }; System.out.println("Price is " + price);
A switch expression can also use switch statement syntax, that is, case statements followed by a colon as shown below.
Notice there repeating case
to match multiple values is still not required.
String size = "S"; int price = switch (size) { // match multiple values case "S", "M": { // some code yield 500; } case "L", "XL": 700; case "XXXL": 1000; default: -1; }; System.out.println("Price is " + price);
But you cannot mix both these syntaxes in the same switch expression.
Following are the possible compiler errors when using a switch expression and the reason why they are flagged.
1. A switch expression should have a default case
When a switch expression should return a value, there must be a default case present else this error will be raised.
2. Mixing of different kinds of case statements is not allowed
If a single switch expression contains case statements with colon and arrow label, this error will be raised.
3. Invalid expression as statement
Switch expression is returning a value and it is not assigned to a variable on left side
4. yield cannot be resolved to a variable
case block has only one statement which is returning a value and it is preceded with yield as shown below.
case "S", "M" -> yield 500;
To solve this, either surround the yield
statement with curly braces, remove yield
or replace the arrow with a colon.
Revision history
1. switch expression was introduced in java 12 as a preview feature. Preview feature means that it can be removed from future releases.
In java 12, there was no yield
statement.
case
statements could return a value using break keyword followed by the value to return as shown below.
String size = "S"; int price = switch (size) { case "S": break 500; case "L": break 700; default : break -1; }; System.out.println("Price is " + price);
This was also called break with label.
2. In java 13, break with label was removed as it was found to be confusing and yield
keyword was introduced to return value for case blocks, the same that we have looked so far.
You won’t find break with label if you are using java 13 and above.
This was again a preview feature in java 13.
3. In java 14, switch expressions were added as a feature with no changes from those added in java 13.
Thus, final switch expressions can be used as explained in this article.
Hope this was useful, see you in the next post. Do not forget to hit the clap.