Local variables Type Inference in Java

Prabu Subra
AlphaXcode
Published in
2 min readJan 2, 2019

To be short, This post is about a type called var, which is introduced in java 10. Before started using var type, i have analysed and summarised about where to use and not to use var type like as an argument for methods, constructors, Exceptions, lambdas, Streams, etc…

what is var ?

It is used to declare local variables and reduces the boilerplate code.

Is it a new keyword introduced in java ?

The answer is big No, it is not a keyword, a new type called var has created to improve type inference.

Is java becoming dynamic type language like JavaScript ?

No, Added an intelligent for compiler to understand the type of the local variable using its initializer without specifying explicitly.

How are the possible ways to declare local variables?

Examples:-

List<String> list = new ArrayList<String>(); // level 1List<String> list = new ArrayList<>(); // level 2var list = new ArrayList<String>(); // level 3

There are the places to use and not to use. Lets see few of that.

Law of var:-

Properly initialized, Non-array variables can use the luxury of type inference.

Summary:-

Eventually, Java has added few spoons of sugar to an existing Type Inference feature. it is not completely freed developers hands to use var in code, it comes with its own laws. Type inference is not completely new feature in java, it has improved a step to use for local variables,mostly to avoid boilerplate code with less upgrade hurdles. The target source code base shouldn’t contains class or interface, which was named as var and possibility also rare, nearly nothing. It is one of the way(not only way) to declare local variables.

Reference:-

Note:- if you feel something has to be added or wrong, feel free to comment below. Thanks for reading!!!

--

--