Local type inference in Java

A quick look

Thomas Künneth
Tommis Programming Blog
2 min readDec 22, 2019

--

A box made of old key caps
Java devs can use var, too.

I like playing with different programming languages and comparing their features. Java 10 gained local type inference through var. So, let’s take a look how this works. First, you may be asking yourself Why isn’t he writing keyword?. That is, because var is not a keyword but a reserved type name. This means that if you have been using var as a variable name your code won’t break.

What does not work, though, is

Here the initializer is missing, thus the expression makes no sense. The following does not work, either:

Local type inference means that you can use var in methods and blocks, but not for static or instance variables. So, this one works:

I like this new feature quite a bit. Not primarily because we can spare a few characters but because we do not have to repeat ourselves:

It is, however, worth mentioning that in other languages there are debates on when to use var and when to be more specific. If you have something like

it is not immediately clear which type result has. But this matters in other programming languages, too. So, what do you think about var in Java?

A previous version of this article was published 2018/04/02 on my Blogger.com blog Tommis Blog. I deleted the weblog in the wake of the GDPR (General Data Protection Regulation), so the original post is no longer available (or only through the Wayback machine of the Internet Archive).

If not stated otherwise images are © Thomas Künneth

--

--

Thomas Künneth
Tommis Programming Blog

Google Developer Expert for Android. Author. Speaker. Listener. Loves writing.