Local Variable Type Inference with var

Since Java 10, a local variable can be declared with var, and the compiler works out its type from the initializer. It removes repetition such as Map> written twice, but it does not make Java dynamically typed: the type is still fixed at compile time, and the class file is identical. This page shows what var infers, exactly where it is allowed, the cases where it infers something surprising, and when to use it.

Contents

What var does

var (JEP 286, Java 10) tells the compiler: "use the type of the initializer as the type of this variable". In var names = new ArrayList<String>(); the variable's type is ArrayList<String>, exactly as if it had been written out. The type is decided once, at compile time, and never changes; assigning a String to a variable inferred as int is a compile error, just as before.

var is not a keyword but a reserved type name. Existing code that used var as a variable or method name still compiles; only a class or interface named var is no longer allowed.

Where var can be used
PlaceAllowed?Since
Local variables with an initializerYesJava 10
Loop variables: for (var i = 0; ...) and for (var x : items)YesJava 10
try-with-resources variablesYesJava 10
Lambda parameters: (var a, var b) -> ...YesJava 11
Fields, method parameters, return typesNo
Variables without an initializer, or initialized with nullNo

What var infers

The program declares variables with var from different initializers: numeric literals, a string, a generic collection, a map entry in a loop, a diamond with nothing to infer from, and literals with suffixes. It prints the class of each value to show the inferred type.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VarBasics {

    public static void main(String[] args) {
        var count = 10;                              // int
        var price = 9.99;                            // double
        var name = "Ada";                            // String
        var names = new ArrayList<String>();         // ArrayList<String>, not List<String>
        names.add(name);

        // Long generic types are where var helps most
        var groups = new HashMap<String, List<Integer>>();
        groups.computeIfAbsent("even", k -> new ArrayList<>()).add(2);
        for (var entry : groups.entrySet()) {        // Map.Entry<String, List<Integer>>
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        // The inferred types (primitives show up boxed here, inside an Object[])
        Object[] values = {count, price, name, names};
        for (Object v : values) {
            System.out.println(v + " -> " + v.getClass().getSimpleName());
        }

        // var is still static typing: the type is fixed at compile time
        // count = "ten";                            would not compile: count is an int

        // A diamond with var infers Object: usually not what you want
        var mystery = new ArrayList<>();
        mystery.add("x");
        mystery.add(1);
        System.out.println("new ArrayList<>() with var holds anything: " + mystery);

        // Literal suffixes matter
        var big = 3000000000L;                    // long; without L this would not compile
        var ratio = 1.5f;                            // float
        Map<String, Object> types = Map.of("big", big, "ratio", ratio);
        System.out.println(types.get("big").getClass().getSimpleName() + ", "
                + types.get("ratio").getClass().getSimpleName());
    }
}

Output:

Output
even -> [2]
10 -> Integer
9.99 -> Double
Ada -> String
[Ada] -> ArrayList
new ArrayList<>() with var holds anything: [x, 1]
Long, Float
  • 10 gives int, 9.99 gives double and "Ada" gives String. They print as Integer and Double only because they were boxed into an Object[] to call getClass().
  • The biggest win is long generic types: var groups = new HashMap<String, List<Integer>>(), and the loop variable var entry is a Map.Entry<String, List<Integer>> that nobody had to type.
  • var mystery = new ArrayList<>() has nothing to infer the element type from, so it becomes ArrayList<Object> and accepted both a string and a number. With var, put the type argument on the right: new ArrayList<String>().
  • Literal suffixes decide the type: 3000000000L is a long and 1.5f a float.

Where var is not allowed, and proof that nothing changes at run time

The program compiles code that uses var in eight places where it is not allowed and prints javac's errors. It then compiles the same method twice, once with explicit types and once with var, and compares the two class files byte for byte. The second version also names a variable var, to show that this is still legal.

Java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import javax.tools.ToolProvider;

// Compiles var in places where it is and is not allowed, and checks the bytecode
public class WhereVarWorks {

    static final String NOT_ALLOWED = """
            import java.util.function.Supplier;

            class NotAllowed {
                var field = 1;                       // fields
                var method() { return 1; }           // return types
                void param(var x) { }                // method parameters
                void several() {
                    var a = 1, b = 2;                // several variables at once
                }
            }
            """;

    static final String NO_TYPE = """
            class NoType {
                void locals() {
                    var noInit;                      // no initializer
                    var nothing = null;              // null has no type to infer
                    var array = {1, 2};              // an array initializer alone
                    var lambda = () -> 1;            // a lambda needs a target type
                }
            }
            """;

    static final String EXPLICIT = """
            import java.util.ArrayList;
            class Same {
                int run() {
                    ArrayList<String> list = new ArrayList<String>();
                    list.add("x");
                    String var = "var is not a keyword";
                    return list.size() + var.length();
                }
            }
            """;

    static final String WITH_VAR = EXPLICIT
            .replace("ArrayList<String> list =", "var list =")
            .replace("String var =", "var var =");

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("var");
        for (String[] src : new String[][] {{"NotAllowed.java", NOT_ALLOWED},
                {"NoType.java", NO_TYPE}}) {
            compile(dir, src[0], src[1]).lines()
                    .filter(l -> l.startsWith(dir.toString()))
                    .map(l -> l.substring(dir.toString().length() + 1))
                    .forEach(System.out::println);
        }

        Path a = Files.createDirectories(dir.resolve("a"));
        Path b = Files.createDirectories(dir.resolve("b"));
        compile(a, "Same.java", EXPLICIT);
        compile(b, "Same.java", WITH_VAR);
        byte[] explicit = Files.readAllBytes(a.resolve("Same.class"));
        byte[] inferred = Files.readAllBytes(b.resolve("Same.class"));
        System.out.println("explicit types and var compile to identical class files: "
                + Arrays.equals(explicit, inferred) + " (" + explicit.length + " bytes)");
    }

    static String compile(Path dir, String name, String code) throws IOException {
        Path file = dir.resolve(name);
        Files.writeString(file, code);
        ByteArrayOutputStream err = new ByteArrayOutputStream();
        ToolProvider.getSystemJavaCompiler().run(null, null,
                new PrintStream(err, true, StandardCharsets.UTF_8),
                "-d", dir.toString(), file.toString());
        return err.toString(StandardCharsets.UTF_8);
    }
}

Output:

Output
NotAllowed.java:4: error: 'var' is not allowed here
NotAllowed.java:5: error: 'var' is not allowed here
NotAllowed.java:6: error: 'var' is not allowed here
NotAllowed.java:8: error: 'var' is not allowed in a compound declaration
NoType.java:3: error: cannot infer type for local variable noInit
NoType.java:4: error: cannot infer type for local variable nothing
NoType.java:5: error: cannot infer type for local variable array
NoType.java:6: error: cannot infer type for local variable lambda
explicit types and var compile to identical class files: true (433 bytes)
  • Fields, return types and method parameters (lines 4 to 6 of NotAllowed) cannot use var: they are part of a class's API, and their types should be stated, not inferred from an implementation detail. Several variables in one declaration are not allowed either.
  • The four local variables in NoType failed with "cannot infer type": there is no initializer, null has no useful type, {1, 2} needs a declared array type, and a lambda needs a target interface to know what it implements.
  • The two class files were identical: var exists only in the source. There is no run-time cost or difference of any kind.

var in lambdas, loops and with anonymous classes

The program uses var for lambda parameters with annotations, in both kinds of for loop, and for an anonymous class, the one case where var can do something an explicit type cannot.

Java
import java.util.List;
import java.util.function.BiFunction;

public class VarInLambdas {

    @interface NonNull {
    }

    public static void main(String[] args) {
        // Java 11: var in lambda parameters, which allows annotations on them
        BiFunction<Integer, Integer, Integer> add = (@NonNull var a, @NonNull var b) -> a + b;
        System.out.println("add: " + add.apply(2, 3));

        // var in for loops
        for (var i = 0; i < 2; i++) {
            System.out.print("i=" + i + " ");
        }
        System.out.println();

        // An anonymous class type can only be held by var, which keeps its extra members
        var point = new Object() {
            int x = 3;
            int y = 4;
        };
        System.out.println("anonymous fields via var: " + (point.x + point.y));

        List<String> words = List.of("alpha", "beta");
        for (var w : words) {
            System.out.println(w.toUpperCase());
        }
    }
}

Output:

Output
add: 5
i=0 i=1 
anonymous fields via var: 7
ALPHA
BETA
  • Lambda parameters can already omit their types, so (var a, var b) adds nothing on its own. Its purpose (Java 11, JEP 323) is to allow annotations or final on the parameters, which need a type position to attach to. All parameters must then use var.
  • var point = new Object() { int x = 3; int y = 4; } keeps the anonymous class type, so point.x compiles. With Object point = ... the fields would be unreachable. It is a curiosity rather than a recommended technique; a local record is clearer.

Where the inferred type comes from

The inferred type is always the static type of the initializer expression, the type the compiler sees, never the class of the object at run time. That rule explains several results that surprise people. The program uses overloaded methods, which are chosen by static type, to reveal what var inferred, and then shows three more consequences of the rule.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class InferenceSource {

    static List<String> loadNames() {                 // declared to return List
        return new ArrayList<>(List.of("Ada", "Linus"));
    }

    // Overloads are chosen by static type, so they reveal what var inferred
    static String staticType(List<String> list) {
        return "List<String>";
    }

    static String staticType(ArrayList<String> list) {
        return "ArrayList<String>";
    }

    public static void main(String[] args) {
        // 1. var uses the STATIC type of the expression, not the runtime class
        var names = loadNames();
        var created = new ArrayList<String>();
        System.out.println("var names = loadNames(): runtime class "
                + names.getClass().getSimpleName() + ", static type " + staticType(names));
        System.out.println("var created = new ArrayList<String>(): static type "
                + staticType(created));

        // 2. Mixed numeric operands widen: int and long make a long
        int small = 5;
        long large = 5000000000L;
        var mixed = true ? small : large;
        System.out.println("true ? int : long is " + ((Object) mixed).getClass().getSimpleName()
                + " " + mixed);

        // 3. A loop counter inferred from 0 is an int, even if the bound is a long
        long limit = Integer.MAX_VALUE + 3L;
        long steps = 0;
        for (var i = Integer.MAX_VALUE - 1; i < limit; i++) {     // i is an int
            if (++steps > 4) {
                System.out.println("int counter wrapped to " + i + "; stopped after " + steps);
                break;
            }
        }

        // 4. Lambdas and method references need a target type: give it with a cast
        var length = (Function<String, Integer>) String::length;
        System.out.println("length of \"varargs\": " + length.apply("varargs"));
    }
}

Output:

Output
var names = loadNames(): runtime class ArrayList, static type List<String>
var created = new ArrayList<String>(): static type ArrayList<String>
true ? int : long is Long 5
int counter wrapped to -2147483646; stopped after 5
length of "varargs": 7
  • loadNames() is declared to return List<String>, so var names is a List<String>, even though the object is an ArrayList. var created = new ArrayList<String>(), on the other hand, is an ArrayList<String>, because that is the type of a constructor call. The overload chosen for each shows the difference.
  • A conditional with an int and a long branch has type long, so mixed is a long even though the int branch was taken.
  • for (var i = Integer.MAX_VALUE - 1; i < limit; i++) made i an int, because its initializer is an int; the long bound does not matter. The counter wrapped around to a negative number, and without the safety stop the loop would never end. Write long i (or var i = 0L) when the bound is a long.
  • A method reference or lambda has no type of its own, so var f = String::length does not compile. A cast supplies the target type, but at that point declaring Function<String, Integer> f is clearer.

Pitfalls: what var infers that you might not expect

Each case in this program compiles and runs, and each infers a type that differs from what a reader might assume.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class VarPitfalls {

    @SuppressWarnings("lossy-conversions")      // the lossy += below is the point of the demo
    public static void main(String[] args) {
        // 1. The type comes from the initializer: 0 makes an int, and += hides a cast
        var total = 0;
        for (double price : new double[] {0.99, 1.49, 2.75}) {
            total += price;                           // compiles: total = (int) (total + price)
        }
        System.out.println("total of 0.99 + 1.49 + 2.75 with var total = 0: " + total);

        // 2. var takes the concrete class, not the interface
        var names = new ArrayList<String>();          // ArrayList<String>
        List<String> declared = new ArrayList<>();    // List<String>
        declared = List.of("can switch implementations");
        // names = List.of("x");                      would not compile: not an ArrayList
        System.out.println("declared List reassigned: " + declared + "; names stays "
                + names.getClass().getSimpleName());

        // 3. char arithmetic produces an int
        var next = 'a' + 1;
        System.out.println("var next = 'a' + 1 is " + next + " ("
                + ((Object) next).getClass().getSimpleName() + ")");

        // 4. A conditional can infer a type you would never write
        boolean ordered = true;
        var items = ordered ? List.of(3, 1, 2) : Set.of(3, 1, 2);
        System.out.println("inferred a common supertype of List and Set: size " + items.size()
                + ", contains 2: " + items.contains(2));
    }
}

Output:

Output
total of 0.99 + 1.49 + 2.75 with var total = 0: 3
declared List reassigned: [can switch implementations]; names stays ArrayList
var next = 'a' + 1 is 98 (Integer)
inferred a common supertype of List and Set: size 3, contains 2: true
  1. var total = 0 made total an int, and total += price silently cast each sum back to int, so 0.99 + 1.49 + 2.75 gave 3 instead of 5.23. JDK 20 added the javac warning -Xlint:lossy-conversions for exactly this ("implicit cast from double to int in compound assignment is possibly lossy"); the program suppresses it to show the bug. Write var total = 0.0, or declare double total.
  2. var names = new ArrayList<String>() has type ArrayList<String>, not List<String>, so it cannot later be assigned a List.of(...) or a LinkedList. For local variables this rarely matters; it is one reason var is not allowed for fields.
  3. var next = 'a' + 1 is an int (98), because char arithmetic is done in int.
  4. A conditional between a List and a Set inferred their common supertype, an intersection of Collection and other interfaces that cannot even be written in Java. It works, but a reader cannot tell what the type is.

When to use var

The OpenJDK project published style guidelines for var alongside JEP 286. Their core idea is that var should make code easier to read, which depends on whether the type is obvious from the right-hand side or from a good variable name.

Guidelines for var
Good useAvoid
var users = new HashMap<String, List<User>>();: the type is on the rightvar result = service.process(input);: the type is hidden in another file
for (var entry : map.entrySet()): long, obvious generic typesvar list = new ArrayList<>();: becomes ArrayList<Object>
try (var in = Files.newInputStream(path))var total = 0; when fractions will be added
Intermediate values with clear names in long chainsShort names such as var x that carry no meaning
Local variables with a small scopeVariables used far from their declaration

var does not change how Java works, only how much you type; the related pages on generics and lambdas cover the type rules it relies on.