How does the var keyword (local variable type inference, introduced in Java 10) work, and what specific restrictions apply to where it can and cannot be used, given Java remains a statically-typed language?
Short answer
var lets the compiler infer a local variable's static type from its initializer expression at compile time (NOT a dynamic/untyped variable the way JavaScript's var behaves -- the inferred type is fixed permanently at compile time, and the variable remains just as strictly…
Advertisement
AModel answer
var lets the compiler infer a local variable's static type from its initializer expression at compile time (NOT a dynamic/untyped variable the way JavaScript's var behaves -- the inferred type is fixed permanently at compile time, and the variable remains just as strictly, statically typed as if you'd written the type explicitly) -- var is restricted to local variables with an initializer present (var x; with no initializer is illegal, since there'd be nothing to infer the type FROM), cannot be used for method parameters, return types, or fields, and using it with certain expressions (like a lambda or an array initializer without an explicit type context) can be ambiguous or disallowed since the compiler needs enough contextual information to actually determine a concrete type.
var list = new ArrayList<String>(); // inferred as ArrayList<String>, fully statically typed thereafter
list.add("hello");
// list.add(42); // still a COMPILE ERROR -- var doesn't remove type safety, only removes explicit type-writing
// var x; // ILLEGAL -- no initializer to infer the type from
// var lambda = () -> System.out.println("hi"); // ILLEGAL -- ambiguous, no concrete inferable typeReal-world example
A team adopts var consistently for local variables with sufficiently descriptive right-hand-side expressions (like var customers = customerRepository.findAll()), improving code conciseness and reducing redundant type-name repetition, while deliberately avoiding var where the inferred type wouldn't be immediately obvious from context alone (like var result = someMethod(), where the actual returned type isn't clear without checking the method signature).
Likely follow-ups
- What's the JDK style guideline recommendation for when var actually improves versus hurts code readability?
- Why can't var be used for a lambda expression's target variable directly, given lambdas already require a target type for other purposes?
Related topics