Going Beyond Java 8: Local Variable Type Inference (var)

According to some surveys, such as JetBrains's great survey, Java 8 is currently the most used version of Java, despite being a 2014 release.

What you are reading is one in a series of articles titled 'Going beyond Java 8,' inspired by the contents of my book, Java for Aliens. These articles will guide you step-by-step through the most important features introduced to the language, starting from version 9. The aim is to make you aware of how important it is to move forward from Java 8, explaining the enormous advantages that the latest versions of the language offer.

Local Variable Type Inference: Declare Var, Not War

Java is changing rapidly, and with the six-month release cycle, we are getting new features to try with every release. In Java 10, local variable type inference was added. It was basically aimed at reducing boilerplate code and improving readability when declaring local variables with initializers.

Programs must be written for people to read and only incidentally for machines to execute
Harold Abelson

26 Items for Dissecting Java Local Variable Type Inference (Var Type)

This article is also part of my book Java Coding Problems.
Image title

The Java Local Variable Type Inference (LVTI), or shortly, the var type (the identifiervaris not a keyword, is a reserved type name), was added in Java 10 via JEP 286: Local-Variable Type Inference. As a 100 percent compile feature, it doesn't affect bytecode, runtime, or performance. Mainly, the compiler will inspect the right-hand side and infer the concrete type. It looks at the right-hand side of the declaration, and if there is an initializer, then it simply uses that type to replacevar. Addtionally, it is useful to reduce verbosity, redundancy, and boilerplate code. It is also meant to speed up the ceremonies involved while writing code. For example, it is very handy to writevar evenAndOdd =...instead of Map <Boolean, List <Integer>> evenAndOdd.... Depending on the use case, it has a trade-off in code readability that is covered in the first item below.