DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. JDK 12 – JEP 325 Switch Expressions

JDK 12 – JEP 325 Switch Expressions

From statement to expression — learn more about the evolution of switch in JDK 12.

Mohamed Sanaulla user avatar by
Mohamed Sanaulla
CORE ·
Apr. 23, 19 · News
Like (5)
Save
Tweet
Share
12.72K Views

Join the DZone community and get the full member experience.

Join For Free

JDK 12 went GA on March 19, 2019, keeping its word on shorter release cycles and frequent releases. The features part of the release can be found here. One of the interesting features for developers is the “JEP 325 Switch Expressions,” which is available as a preview feature.

A preview feature, as defined here, is:

"A preview language or VM feature is a new feature of the Java SE Platform that is fully specified, fully implemented, and yet impermanent. It is available in a JDK feature release to provoke developer feedback based on real world use; this may lead to it becoming permanent in a future Java SE Platform."

In this article, I will show you how switch has evolved from being a statement to an expression. A statement is something that executes but doesn’t evaluate to some value, whereas expression is something that, on execution, evaluates to a value:

//Statement
System.out.println("This is a statement");

//Expression
6 + 5;


Switch as Expressions

The syntax for switch as an expression has changed:

Object switchResult = switch ( variable ) {
    case choice1 -> result1;
    case choice2 -> result2;
    default -> resultDefault;
}


In addition to the above use of a switch, it can be used as a statement as well:

switch( variable ) {
    case choice1: 
      doSomeThing(); 
      break;
    case choice2:
      doOtherThing();
      break;
    default:
      doDefaultThing();
}


I am not going into the motivation for introducing the switch expressions. You can read about it here. The remaining part of the article will demonstrate how the switch can be used as an expression. The following code snippet shows the use of switch as an expression. Be sure to observe that switch now is yielding a value, which, in this case, is boolean:

public static boolean isHealthy(String food){
    return switch (food){
        case "Fruit"  -> true;
        case "Vegetable" -> true;
        case "Pizza" -> false;
        case "Burger" -> false;
        case "Pulses" -> true;
        case "Soft Drink" -> false;
        default -> false;
    };
}

System.out.printf("Fruit is %s\n" , isHealthy("Fruit"));


From the code snippet above, we can see that the expression used in the switch can now be a string as well. This is applicable for both in the statement and the expression.

If the possibility of the values of the expression being evaluated is not a fixed set, then we need to provide the default block. If we are using an enum as switch expression, then we don’t need to provide a default case because the possible outcomes in the enum are limited to the enum values. This is shown in the example below:

enum Food {
    Fruit, Vegetable, Pizza, Burger, Pulses, Soft_Drink
}

public static boolean isHealthEnumVersion(Food food){
    return switch (food){
        case Fruit -> true;
        case Vegetable -> true;
        case Pizza -> false;
        case Burger -> false;
        case Pulses -> true;
        case Soft_Drink -> false;
    };
}

System.out.printf("Pizze is %s\n", isHealthEnumVersion(Food.Pizza));


Another example where we put the result of method evaluation as an expression in the switch:

public static int evaluateLunch(Food food){
    return switch (isHealthEnumVersion(food).toString()){
        case "true" -> 10;
        case "false" -> 5;
        default -> 0;
    };
}

System.out.printf("Your food received %d points\n",
        evaluateLunch(Food.Burger));


Block of Code as Case Evaluation

In the previous examples, we saw the case mapped against single line expressions. How do we deal with when we need a block of code to be evaluated for the case?

public static PreparedFood prepareFood(Food food){
    return switch (food){
        case Pizza -> {
            System.out.println("doing pizza related operations");
            break new PreparedFood(food);
        }
        case Burger -> {
            System.out.println("Doing burger related operations ");
            break new PreparedFood(food);
        }
        default -> {
            System.out.printf("Doing %s related operations\n",
               food.toString());
            break new PreparedFood(food);
        }
    };

}


You can notice that the break has been enhanced to accept a parameter, which becomes the result of the evaluation of the code block against the case.

Switch as an Expression Using the Old Syntax

We can stick to the old syntax of switch i.e without the -> symbol, as shown below:

public static int evaluateLunchOldWay(Food food){
    return switch (isHealthEnumVersion(food).toString()){
        case "true": break 10;
        case "false":  break 5;
        default: break 0;
    };
}


The complete code for this article can be found here.

Java (programming language) Java Development Kit

Published at DZone with permission of Mohamed Sanaulla, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Should You Know About Graph Database’s Scalability?
  • Top Five Tools for AI-based Test Automation
  • Learning by Doing: An HTTP API With Rust
  • 3 Ways That You Can Operate Record Beyond DTO [Video]

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: