Java 10: Local Variable Type Inference

Nuwan Zen
2 min readMar 29, 2021

Java 10 allows you to use var as type variable instead of real type name.

Photo by Chamindu Perera on Unsplash

You can write

List<String> list=new ArrayList<String>();

as

var list = new ArrayList<String>();

Does this mean Java support dynamic typing, no it inferences the type from the initialization. If you look at the de-compiled code var is replaced.

ArrayList<String> list = new ArrayList();

To confirm try to set list variable to different type such as

list = "Test string type";

You will get an error immediately saying required type is Required type:
ArrayList <java.lang.String> but not a String.

Also you want be able just create the variable like this

var list;

Again you will see an error saying

Cannot infer type: ‘var’ on variable without initializer

This confirms there is a type inference happens and internally it goes back to static typing.

Lambda style type inferences will not work.

var test= s->s.length();

will produce following error

java: cannot infer type for local variable test
(lambda expression needs an explicit target-type)

anonymous class as a type

Did you ever thought of using anonymous class as a type, yes now its possible,

var runnable = new Runnable(){
@Override
public void run() {
System.out.println("test");
}
};
runnable.run();

Non Denotable Types

var person = new Object(){
class Name{ }
Name name;
};
person.name = person.new Name();

Non-denotable types — that is to say types that can exist within your program, but for which there’s no way to explicitly write out the name for that type. anonymous classes too comes under this.

Read my other blogs:

--

--

Nuwan Zen

Sometimes A software Engineer, sometimes a support engineer, sometimes a devops engineer, sometimes a cloud engineer :D That’s how the this life goes!