The var Identifier (Java 10 and Later)


Java 10 was first released in Mar 2018 and its language update can be considered quite new at the time of this writing.  An important part of the release was about the new var identifier.

According to the Oracle's Java release document, "you can declare local variables with non-null initializers with the var identifier."

Consider this example of declaring a variable with an assignment of a non-null initializer:
URL url = new URL ("http://www.amazon.com/");

Instead of specifying the Class or primitive type before a variable, with Java 10 or later we can declare the variable by using the var identifier:
var url = new URL ("http://www.amazon.com/");

The Class of the new variable url is automatically inferred from the context. Declaring the datatype before the variable is no longer necessary.

Now consider the variables that I declared with a generic class type in my earlier post:
GenericArrayStat <Integer> numHousesSold = new GenericArrayStat <> (iNumArray);
GenericArrayStat <Integer> soldPrices = new GenericArrayStat <> (dNumArray);

By using the var identifier, we can shorten the declarations in this way:
var numHousesSold = new GenericArrayStat <Integer> (iNumArray);
var soldPrices = new GenericArrayStat <Double> (dNumArray);

While the var identifier looks convenient for the assignments of new objects, it possibly requires you to pay more attention to the assignments of existing ones.

Consider these declarations in the traditional way that the Class or primitive type are clearly defined in the code:
Path filePath = Paths.get(fileName);
bytes[] fileBytes = Files.readAllBytes(filePath);

Now compare the new var declarations with above:
var filePath = Paths.get(fileName);            // infers Path
var fileBytes = Files.readAllBytes(filePath);  // infers bytes[]

By using var declarations, we can see that the class and primitive type of the assigned variables are not included in this case.  However, we have the option to include them in the comments.

In recent years, there have been newer languages aiming at simplifying language verbosity.  It is good that Java provides with the flexibility on how to code.  We want just enough meaning in the code, and we want consistency.  Choose the way you like.

Comments

Popular posts from this blog

Finding Median by Stream

Factorial by Different Styles in Java

Reduction by Java Stream