Sunday, June 02, 2019

Java 12: Switch Expressions

In Java 12, the switch statement has been enhanced so that it can be used as an expression. It is now also possible to switch on multiple constants in a single case, resulting in code that is more concise and readable. These enhancements are a preview language feature, which means that they must be explicitly enabled in the Java compiler and runtime using the --enable-preview flag.

Consider the following switch statement:

int result = -1;
switch (input) {
  case 0:
  case 1:
    result = 1;
    break;
  case 2:
    result = 4;
    break;
  case 3:
    System.out.println("Calculating: " + input);
    result = compute(input);
    System.out.println("Result: " + result);
    break;
  default:
    throw new IllegalArgumentException("Invalid input " + input);
}

In Java 12, this can be rewritten using a switch expression as follows:

final int result = switch (input) {
  case 0, 1 -> 1;
  case 2 -> 4;
  case 3 -> {
    System.out.println("Calculating: " + input);
    final int output = compute(input);
    System.out.println("Result: " + output);
    break output;
  }
  default -> throw new IllegalArgumentException("Invalid input " + input);
};

As illustrated above:

  • The switch is being used in an expression to assign a value to the result integer
  • There are multiple labels separated with a comma in a single case
  • There is no fall-through with the new case X -> syntax. Only the expression or statement to the right of the arrow is executed
  • The break statement takes an argument which becomes the value returned by the switch expression (similar to a return)

Saturday, June 01, 2019

Using Java 12 in Eclipse

1. Install JDK 12

Link: https://www.oracle.com/technetwork/java/javase/downloads/jdk12-downloads-5295953.html

2. Install Eclipse 4.11

Link: https://download.eclipse.org/eclipse/downloads/drops4/R-4.11-201903070500

3. Install Eclipse Java 12 Support

Start Eclipse and go to Help > Install New Software. Add Update Site: https://download.eclipse.org/eclipse/updates/4.11-P-builds. Install Eclipse Java 12 support for 2019-03 development stream from the list of available software

4. Add Java 12 JRE to Eclipse

Go to Window > Preferences, navigate to Java > Installed JREs and add the Java 12 JRE (that you installed in Step 1). Tick the box to make it the default JRE

5. Upgrade Compiler Compliance Level

In your preferences, go to Java > Compiler and select "12" as the "Compiler compliance level". In addition, tick "Enable preview features".

That's it! Now you can try out Switch Expressions!