New in Java 12

03.12.2018 Tom Trapp
Tech java jvm goodtoknow

Java 12 is here! Get to know the new features here.

New switch case

There are two big innovations regarding the switch / case function with Java 12, both are currently in the preview status.

  • The popular Arrow syntax can now also be used for switch / case statements. This makes break statements unnecessary, which is really sexy.
  • switch statements can now have a return value and can thus be used directly as an expression

The traditional way

switch(fruit){
        case"apple":
        case"banana":
        System.out.println("tasty");
        break;
        case"citron":
        System.out.println("uuugh");
        break;
default:
        System.out.println("ok");
        }

The new way

// Arrow syntax
switch(fruit){
        case"apple","banana"->System.out.println("tasty");
        case"citron"->System.out.println("uuugh");
default ->System.out.println("ok");
        }

// Switch as an Expression
        String taste=switch(fruit){
        case"apple","banana"->"tasty";
        case"citron"->"uuugh";
default ->"ok";
        }

Raw String literals

Another new feature which has changed directly 'The way of coding' raw string literals.

This is currently also a preview feature, it is now possible to easily create multiline strings or strings with special characters.

Such raw string literals are generated with backticks. The new align method even makes it possible to align multiline strings correctly (Indents).

Sure, at first glance this is a great feature, but the 'Real World Use-Case' is not immediately apparent. In this way, SQL queries or similar can possibly be formatted in the future.

The traditional way

// traditional string
final String s1="hello world";

// traditional multiline string
final String s2="line1\nline2";

The new way

// raw string literals
final String rsl1= `hello world`;
final String rsl2= `
        line1
        line2
        line3`;
final String rsl3= ``backtick`inside``;
final String rsl4= `\n`;

        System.out.println(rsl1);
        System.out.println(rsl2);
        System.out.println(rsl3.align());
        System.out.println(rsl4);

        System.out.println(rsl1.length());
// will print :
hello world

        line1
        line2
        line3
        line1
        line2
        line3

        backtick`inside
        2

New preview feature

With Java 12 there is a new feature type called preview. If you want to use these features, you can activate them using the command line parameter -enable-preview.

There are two things to keep in mind regarding the preview features:

  • The functionality can change
  • A preview feature can be promoted to an official feature or completely removed

This text was automatically translated with our golang markdown translator.

Tom Trapp - problem solver, innovator, athlete. Tom prefers to work on modern software all day long and attaches great importance to objectively clean, lean code.