Java 10: Local Variable Type Inference

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

Photo by Chamindu Perera on Unsplash

You can write


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.

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

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

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.

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,

Non Denotable Types

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:



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
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!