What is the var keyword in Java 10, and when should you avoid it?

var lets the compiler infer the type of a local variable from the value on the right-hand side. Java is still statically typed: the type is fixed at compile time, and var only saves you from writing it twice.

Key Points: • var works only for local variables with an initializer, for-each loop variables, and (from Java 11) lambda parameters. • It cannot be used for fields, method parameters or return types, and not with null or an array initializer alone. • The inferred type is the exact type of the expression. var list = new ArrayList<String>() makes list an ArrayList, not a List. • var is a reserved type name, not a keyword, so existing variables called var still compile. • Avoid it when the type isn't obvious from the right-hand side, for example var result = service.process(); and readers have to guess what came back.

Code Example:

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

public class VarDemo {

    public static void main(String[] args) {
        var names = new ArrayList<String>();          // ArrayList<String>
        names.add("Java");
        names.add("Spring");

        var scores = new HashMap<String, List<Integer>>();
        scores.put("Asha", List.of(90, 85));

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

        var count = 10;                               // int
        var price = 99.5;                             // double
        System.out.println(names + " " + count + " " + price);

        // var x;            // compile error: no initializer
        // var y = null;     // compile error: type cannot be inferred
    }
}

Output:

Asha -> [90, 85] [Java, Spring] 10 99.5

Good to Know: A good one-line answer is "var reduces noise, not type safety". Mention that var shines with long generic types such as Map<String, List<Integer>>, and that teams usually avoid it when the right-hand side is a method call whose return type is unclear.

Interview Tip: A concise interview answer is:

"var, from Java 10, lets the compiler infer a local variable's type from its initializer; the type is still fixed at compile time. It only works for local variables with an initializer, loops and lambda parameters, and I avoid it when the type isn't obvious from the right-hand side."

Previous question: What are the differences between Java 8, 11, 17 and 21, and why should a project upgrade?

Next question: What are records in Java, and when should you use them?

More Java 17 and 21 Features interview questions

All Java 17 and 21 Features questions