java is smart – using var

I was working on some code and seeing how many local variables I could substitute with var. I was a little surprised to learn that the below compiles. It makes sense to me that mags is good because the type is there. It’s cool that years and sorted can infer the type of Integer as well.

package lists;

import java.util.*;

public class Magazines {

    public static void main(String[] args) {
        var mags = new HashMap<String, Integer>();
        mags.put("People", 1974);
        mags.put("Readers Digest", 1922);
        mags.put("The Economist", 1843);

        var years = mags.values();

        var sorted = new ArrayList<>(years);
        Collections.sort(sorted);

        int first = sorted.get(0);
        System.out.println(first);
    }
}

local variable type inference with instance and static initializers

Local type variable inference is the formal name of “var” in Java. From the name, you might deduce some things about allowed or disallowed locations. For example, a local variable in a method is allowed and an instance variable declaration is not.

Scopes that are even more granular are also allowed such as inside a for loop or try with resources statement.

I learned today that instance and static initializers are allowed as well.

public class LVTI {
public int myValue;
{
var temp = 3;
myValue = temp;
}
}
}

In hindsight, this makes sense. An initializer is a block of code. Which can have local variables.

For more on local variable type inference, please see the official style guidelines.

What type is a var?

Java 10 introduced “var” where the type of the variable is implied. This leads to some tricky scenarios.

We first learn that “var” can replace the type. That means these two code blocks are equivalent.

int a = 9;
int b = a;
var a = 9;
int b = a;

Ok. So far so good. Now we have this code:

short a = 9;
short b = a;

So we substitute var and the code no longer compiles!

var a = 9;
short b = a;

What’s going on? Well, Java is only using the one line to figure out the type. Since int seems like a reasonable default, variable a is an int. Until of course, we get to the next line and it isn’t.

This would compile, but defeats the purpose of using var. So be careful!

var a = (short) 9;
short b = a;