Java 10 in 5 minutes

From Java 9, Oracle will release a new version of Java every 6 months, starting with Java 10, which is to be released on march 20, 2018.

This blog highlights the major language and API changes in Java 10.

Local variable type inference

For local variables, specifying the type is not always needed anymore.

//java 9
String text = "Hello World";
//java 10
var text = "Hello World";

The Java compiler will infer the type of the variable from the right-hand side of the statement.
This will also work on method calls:
//assuming that myMethod returns a String
var stringResult = myMethod();


You can also use this on for loops:
//local variables in for loops
var stringList = List.of("a", "b", "c");
for (var element: stringList) {
  System.out.println(element);
}
for (var i = 0; i < 10; i++) {
  System.out.println(i);
}


Local variable type inference won’t compile in the following cases:
//won't compile, no type can be determined
var x; 

//won't compile on method reference
var name2 = Main::getName;

//won't compile on null reference
var nullValue = null;

//won't compile on array initializer
var stringArray = {1, 2}; 

A word of caution

Correctly naming variables becomes even more important when using local variable type inference, so State Your Intentions when introducing a variable!

API changes

The List, Set and Map interfaces now support copy methods which return unmodifiable collection copies.

//java 9
List newList = Collections.unmodifiableList(oldList);
//java 10
List newList = List.copyOf(oldList);

Collectors now also support collecting to unmodifiable collections for List, Set and Map.
//java 9
List newList =  Collections.unmodifiableList(oldList.stream().collect(Collectors.toList()));
//java 10
List newList = oldList.stream().collect(Collectors.toUnmodifiableList());

Try it out

  • You can download an early access release of Java 10 here.
  • IntelliJ 2018.1 supports Java 10. Download it here.
  • We provided a demo java 10 application on GitHub. Download it here.

Leave a Reply

Your email address will not be published.