This article is also part of my book Java Coding Problems.
The Java Local Variable Type Inference (LVTI), or shortly, the var
type (the identifiervar
is 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.