Back
23 октобра, 2020

After Java 8: Part 3 — Java 10

Share:

This is the third in a series of articles about changes in Java ecosystem after version 8. In the previous article, we covered changes in java 9. In this article, we will discuss changes in the language that came with version 10.

Java 10 is released in March 2018, it is non LTS release with the end of support in September 2018 for Oracle Open JDK and Oracle JDK. It is the first release in the new 6 months release cycle and therefore contains only minor, incremental changes.

Local variable type inference

Java 10 introduced var as a reserved type name that can be used to initialise local variable without declaring it explicitly. The idea of var is to reduce boilerplate code and increase readability.

//declaring variable explicitly
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("path/file"));//using var
var someString = "someString";

At compile time, the compiler infers a type based on the initialisation statement.

//var after compilation 
String someString = "someString";

From Java 10, creating class or interface with name var is not possible because var is a reserved type name. However, class or interface with name Var (upper case ) can be created.

public class var {
//compile error: var cannot be used for type declarations
}
public class Var {
//compiles successfully
}

How var cannot be used in code:

  • var cannot be used as a field type, method parameter type or constructor parameter type.
  • Because var is a reserved type name, methods and fields can be named var
class SomeClass {
private int var;
public void var() {
}
}
  • var must be initialized
//compile error, var must be initialised
var x;
  • var cannot be referenced to a null
//compile error, cannot infer type, var initialiser is null 
var x = null;
  • var is not allowed in a compound declaration.
//compile error, cannot infer type
var i, j =0;
  • var cannot replace the type of lambda expression

var lambda = x -> x > 3

How to and how not to use war:

Think twice before using it. Does it really add to readability off your code?

If you decide to use it, here are some advices that can help you to use it better, and to annoy the person who will be doing maintenance of that code a little bit less:

  • Choose a good variable name
var x = dbConnection.executeQuery(query);  //bad examplevar users = dbConnection.executeQuery(query); //good example
  • Use good initializer information
var user = get();  //bad examplevar users = getUsers(); //good examplevar user = getUser(); //good example
  • Take care with <>
var users = new ArrayList<>();  //bad example - ArrayList


Share: