New Java 10 Language Feature: Local-Variable Type Inference (var)!

Adrian D. Finlay
Nov 15, 2017 · 7 min read
ATC2016 Innovation Lab

Not Caught up to Java 9? Learn more below:

var x = new HashMap<String,Integer>();
//inferred to be HashMap<String,Integer>
HashMap<String,Integer> x = new HashMap<String,Integer> ();
public void doGet() { ... }
public void doPost() { ... }
...var r = doMath();
//No clue just by looking at this line alone what type this returns!
//Where did it come from? Not immediately obvious to second hand readers of your code in large projects.
Map<String,Integer> x = new HashMap <> ();
// Note that we do not need to repeat the paramater arguments
// in the RHS diamond operator as it is induced from the
// RHS return type.
var x = new HashMap<> ();
//Legal!

Some Restrictions

1) Use falling outside of these categories

var x; //No!!! -- Terrible code anyway!
var x=0,y=0; // no!
var x = null; //No!
var y = funcReturningNull(); //No!
// We cannot infer the type.var x = (Object) null; // This, however, works ;)
//Credit to Olivier Gauthier for this observation.
var x=0; //Inferred to be of type 'int'
var x="c"; //No! - incompatible types!

Some Other Things to Know

  • Capture variables used with var are mapped to their supertypes. Any type arguments, if specified are replaced with bounded wildcards.
  • Some Non-Denotable types (like Anonymous Classes) can be inferred by var.

What is var itself?

One might be tempted to believe that var is a keyword. This is in fact, not true. var in Java will a reserved type name. After all, when we type var we are typing it where a type identifier would otherwise be.

Grab JDK 10

To get the early the current builds for JDK 10 documentation, visit here:

$bash on SUSE Linux. I created a folder with some scripts for automating switching between JDKs and openJDKs.

Let’s play with var

Some JShell. Notice that var only works with JDK 10 (of course)!

Some compiled examples.

for (var x=0; x<6; x++) { }

Some Current Error Messages of Failures with var

var v () { return new Object(); } 
//error: 'var' is not allowed here
var class vc { }
//error: 'var' is not allowed here

Where to learn more about Java 10

Curious about the targeted new features in JDK 10? Check them out, here.

Want the source? Grab it here.

Java 11 Sneak Peek

See how this feature is upgraded in Java 11!

How do you like var with Java 10?

Looney Tunes Ending [4]

The Java Report

A curation of contemporary content on all things Java, JavaFX, JavaEE, and JVM technologies.

Adrian D. Finlay

Written by

@thewiprogrammer. Lover of learning, programming. Tech writer, Java aficionado. Proud mango, fishing, NBA addict! & more. Network w/ me @ bit.ly/AdfNtWk

The Java Report

A curation of contemporary content on all things Java, JavaFX, JavaEE, and JVM technologies.