What is new in Java 12?

- Tom Trapp

Java 12 is coming! Get to know the coming features here, we'll update the list as soon as another interesting topic is approved.

Major update to the switch case

There are two major changes regarding the switch functionality coming with Java 12, currently in preview state:

  • Arrow syntax which removed the need of break statements (which is pretty awesome!)

 

  • Switch statements can return a value and can be used as an expression
//The old way

// traditional switch
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 feature which directly changes the way of coding is "Raw String Literals". This is also a preview feature (currently), you are able to easily use String with special characters and even multiline Strings. Such raw string literals are created with a backtick `. The new method "align" coming with the String class makes it easy to align muliline indented text.

 

 

This is quite a cool feature, but let's be honest, I'm not seeing the "real world" use case for raw string literals.

// The old 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

Preview Features???

As of Java 12 there is a new feature type called "preview" coming. If you want to use a feature tagged as "preview", you have to enable them by command line param "--enable-preview" to your JDK.

Two things to keep in mind regarding preview functions:

  • they can change over time
  • they can be "unlocked" as official function or they can be removed