Friday, 11 October 2019

Switch Expressions in Java 12

In Java 12 Switch statement has been extended to be used as either a statement or an expression. In this article we’ll see with some examples how to use this new feature switch expressions.


Java Switch expressions

A new form of switch label, written "case L ->" has been added in Java 12 that allows the code to the right of the label to execute only if the label is matched.

We’ll try to understand this switch expression with an example, initially let’s use traditional switch statement to write a conditional switch-case branch and then use switch expression to see how it simplifies it.

For example if you want to display the quarter, passed month falls into then you can group three case statements where break statement is used with only the last one in the group.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 4;  
  switch(month){
   case 1:    
   case 2:    
   case 3: System.out.println("Quarter 1"); 
     break;
   
   case 4:   
   case 5:     
   case 6: System.out.println("Quarter 2"); 
     break;
   
   case 7:   
   case 8:  
   case 9: System.out.println("Quarter 3"); 
     break;
   
   case 10:     
   case 11:   
   case 12: System.out.println("Quarter 4"); 
      break;
   
   default: System.out.println("Invalid month value passed");
  }
 }
}

Consider some of the pain areas here-

  1. Even if multiple cases have the same end value still you need to write them in the separate lines.
  2. Use of many break statements make it unnecessarily verbose.
  3. Missing a break statement results in an accidental fall-through.

Now let’s write the same example using switch expressions.

public class SwitchCaseDemo {

    public static void main(String[] args) {
        int month = 4;        
        switch(month){
            case 1, 2, 3 -> System.out.println("Quarter 1");         

            case 4, 5, 6 -> System.out.println("Quarter 2");     
        
            case 7, 8, 9 -> System.out.println("Quarter 3");             
             
            case 10, 11, 12 -> System.out.println("Quarter 4");              
            
            default -> System.out.println("Invalid month value passed");
        }
    }
}

Note the changes here-

  1. Multiple case labels can be grouped together now.
  2. Break statement is not required any more. If a label is matched, then only the expression or statement to the right of an arrow label is executed; there is no fall through.
  3. This new switch form uses the lambda-style syntax introduced in Java 8 consisting of the arrow between the label and the code that returns a value.

Note that to use switch expressions feature make sure you have JDK 12 installed. To enable this feature, you’ll need to use the flags --enable-preview and --release 12 when you compile your code.

javac --enable-preview --release 12 SwitchCaseDemo.java

To run the generated class file, you’ll need to pass the --enable-preview flag to the Java launcher.

java --enable-preview SwitchCaseDemo

From Java 12 you can use colon syntax (:) too with multiple case labels but in that case break statement has to be used to avoid fall-through.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  int month = 4;  
  switch(month){
   case 1, 2, 3 : System.out.println("Quarter 1"); 
         break;

   case 4, 5, 6 : System.out.println("Quarter 2");  
       break;
   case 7, 8, 9 : System.out.println("Quarter 3");    
       break;
   case 10, 11, 12 : System.out.println("Quarter 4");     
       break;
   default : System.out.println("Invalid month value passed");
  }
 }
}

Why is it called Switch expression

Now the more pertinent question is why this new feature is called switch expression. As you must be knowing; Statements are essentially “actions” that have to be executed. Expressions, however, are “requests” that produce a value. Same difference applies to switch statement and switch expressions too.

Here is an example showing returning a value from a traditional switch statement.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  String message = "No event to log";
  switch (event) {
      case "Start":
          message = "User started the event";
          break;
      case "Stop":
          message = "User stopped the event";
          break;
  }
  return message;
 }
}

Output

User started the event

Same thing with Java Switch expressions. Since expression itself produces a value so it can be assigned to a variable directly.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  var msg = switch (event) {
      case "Start" ->  "User started the event";
      case "Stop" -> "User stopped the event";
      default -> "No event to log";
  };
  return msg;
 }
}

Output

User started the event

If you want to use colon syntax then you can assign the value directly after break.

public class SwitchCaseDemo {

 public static void main(String[] args) {
  System.out.println(getMessage("Start"));
 }
 private static String getMessage(String event) {
  var msg = switch (event) {
      case "Start" : break  "User started the event";
      case "Stop" : break "User stopped the event";
      default : break "No event to log";
  };
  return msg;
 }
}

Writing statement blocks

If you need to have multiple statements with in a case you can use a statement block enclosed in curly braces.

public class SwitchCaseDemo {

    public static void main(String[] args) {
        int month = 4;        
        var value =switch(month){
             case 1, 2, 3 ->{
                System.out.println("Quarter 1");     
                break "Quarter 1";
            }
            case 4, 5, 6 -> {
                System.out.println("Quarter 2"); 
                break "Quarter 2";
            }
        
            case 7, 8, 9 ->{
                System.out.println("Quarter 3");     
                break "Quarter 3";
            }
             
            case 10, 11, 12 -> {
                System.out.println("Quarter 4");  
                break "Quarter 4";
            
            }
            
            default -> {
                System.out.println("Invalid month value passed");
                break "Invalid month value";
            }
        };
        System.out.println("Value- " + value);
    }
}

That's all for this topic Switch Expressions in Java 12. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. break Statement in Java
  2. Type Wrapper Classes in Java
  3. Ternary Operator in Java
  4. Type Casting in Java
  5. Core Java Basics Interview Questions And Answers

You may also like -

  1. Private Methods in Java Interface
  2. Multi-Catch Statement in Java Exception Handling
  3. Creating a Thread in Java
  4. How HashMap Works Internally in Java
  5. Byte Streams in Java IO
  6. Check if Given String or Number is a Palindrome - Java Program
  7. Spring Boot Hello World Web Application Example
  8. Connection Pooling With Apache DBCP Spring Example

No comments:

Post a Comment