Coffee Talk: Java, News, Stories and Opinions

Feb 4 2019   7:29PM GMT

A quick look at inferred types and the Java var keyword

cameronmcnz Cameron McKenzie Profile: cameronmcnz

Tags:

The biggest language change packaged with the Java 10 release, aka JDK 18.3,¬†was the introduction of the inferred type. This addition, combined with the ability to use the long reserved¬†Java ‘var’ keyword in your code, will have a significant impact on how programs are both read and written.

The case for the Java var keyword

Java has always had a weird syntax to declare variables. A manifest type declaration on the left side must polymorphically match up with the object type provided on the left hand side of the equation. This creates a somewhat verbose and dare I say it, clunky syntax for what is an exceptionally common task.

Java declaration

Java variable declaration without the var keyword

A Java var keyword example

As you can see from that simple code snippet, traditionally developed Java code lends itself to verbosity. But with the use of the var reserved work and the type inference, the code can be cleaned up quite a bit.

Java var keyword

The use of Java inferred types with the var keyword.

With this new syntax, the object type does not need to be explicitly declared on the left hand side of the initialization. Instead, the object type can simply be inferred if you look at the right hand side of the equation, thus the term inferred type. Of course, the right hand side of the equation always has the final say on what type of object is created, so this Java 10 feature doesn’t really change how the Java language works, nor will it have any impact on how code will be interpreted.

In the end, the language change simply drives towards the goal to make Java, a language often criticized for being far too verbose, more readable.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: