Type Inference

Java is statically typed, but you do not always have to write the types: the compiler can often work them out from context. Type inference reduces repetition while keeping every variable's type fixed at compile time. This lesson covers var for local variables (Java 10), the diamond operator, inference for generic methods and lambdas, and the pitfalls that make explicit types the better choice in some places.

Local Variables with var

Since Java 10, a local variable with an initializer can be declared with var. The compiler gives the variable the static type of the initializer, exactly as if you had written it. var is not dynamic typing: the type cannot change later, and assigning a value of another type is a compile error.

// Local variable type inference (var) and other places the compiler infers types.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class InferenceBasics {
    static <T> T firstOf(List<T> items) { return items.get(0); }   // T is inferred per call

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

        Map<String, List<Integer>> scores = new HashMap<>();   // diamond: <String, List<Integer>>
        scores.put("ana", List.of(90, 85));

        for (var entry : scores.entrySet()) {    // Map.Entry<String, List<Integer>>
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        String first = firstOf(names);           // T inferred as String
        System.out.println(first + " " + count + " " + price);

        // Lambda parameters are inferred from the target type; var may annotate them (Java 11+).
        java.util.function.BiFunction<Integer, Integer, Integer> add = (var a, var b) -> a + b;
        System.out.println(add.apply(2, 3));
    }
}

Output:

ana -> [90, 85]
Ana 10 9.99
5

Where var Is Allowed

AllowedNot allowed
Local variables with an initializerFields, method parameters, return types
Enhanced for loop variables and classic for countersVariables without an initializer, or initialized to null
try-with-resources variablesArray initializers such as {1, 2, 3}
Lambda parameters (Java 11+), useful to attach annotationsLambdas assigned directly: var f = x -> x; has no target type

var is a reserved type name, not a keyword, so existing code that uses var as a variable or method name still compiles; it cannot be used as a class name.

Inference with Generics

Generic code benefited from inference long before var. The details of generics themselves are covered in Generics.

The Diamond Operator

Since Java 7, new HashMap<>() takes its type arguments from the declaration it is assigned to, so Map<String, List<Integer>> scores = new HashMap<>(); states the type only once. Combining the diamond with var leaves the compiler nothing to infer from, and it falls back to Object — the first pitfall below.

Generic Methods and Lambdas

When you call a generic method such as firstOf(names), the compiler infers T from the arguments and from the target type of the result. Lambdas work the same way: a lambda has no type of its own, and its parameter types come from the functional interface it is assigned to, its target type. That is why (a, b) -> a + b compiles as a BiFunction<Integer, Integer, Integer>; see Lambda Expressions.

Pitfalls

Surprising Types

var always takes the type of the initializer, which is not always the type you meant:

// var keeps the static type of the initializer, which is not always the type you meant.
import java.util.ArrayList;
import java.util.List;

class InferencePitfalls {
    public static void main(String[] args) {
        var big = 3_000_000_000L;            // without the L suffix this would not compile (int overflow)
        var ratio = 1 / 2;                   // int division: 0, not 0.5
        var exact = 1 / 2.0;                 // double: 0.5
        System.out.println(big + " " + ratio + " " + exact);

        var list = new ArrayList<>();        // ArrayList<Object>: the diamond had nothing to infer from
        list.add("text");
        list.add(42);                        // compiles, because the element type is Object
        System.out.println(list);

        List<String> typed = new ArrayList<>();  // declare the interface type when it matters
        typed.add("only strings");
        System.out.println(typed);

        // var nothing;           // error: cannot infer type without an initializer
        // var nil = null;        // error: null has no usable type
        // var arr = {1, 2, 3};   // error: array initializer needs an explicit type
    }
}

Output:

3000000000 0 0.5
[text, 42]
[only strings]
  • Numeric literals: var x = 1; is an int; write 1L, 1.0 or 1f for other types.
  • Diamond with var: var list = new ArrayList<>(); is an ArrayList<Object>, which accepts anything.
  • Implementation types: var list = new ArrayList<String>(); has type ArrayList, not List, so later code may come to depend on the implementation.

When to Use var

var or an Explicit Type?

Use var when the type is obvious from the right-hand side — a constructor call, a literal, a well-named factory method — or when spelling it out adds noise, as with long generic types in loops. Prefer an explicit type when the initializer is a method call whose result type a reader cannot guess, when the variable's interface type matters more than its implementation, or when the exact numeric type is important. Readability for the next person is the deciding factor; the OpenJDK project's style guidelines for local variable type inference give detailed advice.

Practice

Exercises

  1. Rewrite a method from an earlier lesson with var wherever it is allowed, then restore explicit types wherever the result became harder to read.
  2. Predict the type of each variable: var a = 'x' + 1;, var b = List.of(1, 2.0);, var c = Map.of("k", 1).entrySet();. Check your answers by calling getClass() or hovering in an IDE.
  3. Make firstOf fail to infer a type by calling it with List.of() and assigning the result to var; explain what T becomes.