ReviseAlgo Logo

Modern Java Features

var Keyword

Learn Local Variable Type Inference (var) introduced in Java 10.

Interview: Tests compiler rules regarding var: where it is allowed (local variables only) and where it is prohibited (fields, methods).

Last Updated: June 13, 2026 8 min read

Introduced in Java 10, the var keyword enables Local Variable Type Inference. It allows developers to omit explicit type declarations for local variables, letting the compiler infer the type based on the initializer.

Core Idea

Type inference reduces boilerplate for local variables without sacrificing compile-time static safety.

Why It Matters

Improves code readability when dealing with long, nested generic types (like map entries).

Interview Lens

Tests strict compiler rules: where var is illegal (fields, method arguments, return types).

Compiler Rules and Limitations

  • Local Variables Only: Can only be used for local variables inside methods, constructors, or initializer blocks.
  • Initializer Required: You must initialize the variable immediately (e.g. var x; is illegal).
  • Static Binding: Type is inferred at compile time and is permanent. Java remains a statically-typed language; var is not a dynamic type key like in JavaScript.
  • No Null Initializers: var x = null; is illegal because the compiler cannot infer a type from null.

Code Walkthrough

This program demonstrates valid and invalid usages of type inference.

import java.util.HashMap;

public class VarDemo { // public var field = 10; // ILLEGAL: var is not allowed for fields!

public static void main(String[] args) { // Legal: compiler infers HashMap var map = new HashMap(); map.put("key", 100);

// Legal: compiler infers int var num = 42;

// var name; // ILLEGAL: must initialize immediately! } }

Interview-Relevant Information

Q: Does the var keyword add runtime overhead?
Answer: No. Type inference is a compile-time feature. The compiler determines the type at compilation and writes it explicitly into the .class bytecode. At runtime, the JVM has no concept of var, meaning there is zero performance penalty.

Quick Checklist

Where is the var keyword allowed? Does it affect performance? If yes, you understand type inference.

Use Cases

Simplifying complex generic loop iterators.

Reducing boilerplate inside local variable mappings.

Common Mistakes

Using var when the inferred type is not obvious, making the code hard to read for team members.

Attempting to use var as a parameter type in method signatures, which is a compile error.