Local Variable Type Inference (var)
TL;DR
- Local Variable Type Inference (
var), introduced in Java 10, allows you to omit the explicit type declaration for a local variable. - The compiler automatically infers the type based on the right-hand side of the assignment.
- Java is still 100% statically and strongly typed.
varis just syntactic sugar for the compiler; it is not dynamic typing like in JavaScript.
Concept
Java is famous for its verbose boilerplate. Before Java 10, if you wanted a list of user objects, you wrote:
Map<String, List<User>> userMap = new HashMap<String, List<User>>();
The type Map<String, List<User>> is completely redundant because the compiler can clearly see you are assigning a HashMap to it.
By using var, you tell the Java Compiler: “Look at the value on the right side of the equals sign, figure out what type it is, and lock this variable to that type forever.”
var userMap = new HashMap<String, List<User>>();
Once compiled into bytecode, a var variable is completely indistinguishable from a classically declared variable.
Examples
import java.util.ArrayList;
import java.util.List;
public class VarDemo {
public void processData() {
// 1. Basic inference
var name = "Alice"; // Inferred as String
var age = 30; // Inferred as int
// This will throw a COMPILE error! 'name' is strictly a String.
// name = 42;
// 2. Complex Generics (Where var shines)
var users = new ArrayList<String>(); // Inferred as ArrayList<String>
// 3. Excellent for standard loops
for (var user : users) {
System.out.println(user.toUpperCase());
}
// 4. DANGER: Diamond Operator pitfalls
// Here, the compiler infers ArrayList<Object>, not ArrayList<String>!
// Because the right side (<>) has no type information.
var badList = new ArrayList<>();
}
}
Interview Questions
Q: Can you use var for class fields or method parameters?
A: No! This is a strict limitation. var can only be used for local variables inside a method body (or in for loops/try-with-resources blocks). You cannot use it for class instance variables, method parameters, or method return types. The Java architects explicitly restricted this because public APIs (methods and fields) need explicit, readable contracts. var is only for internal implementation details.
Q: Why does var x = null; fail to compile?
A: Because the compiler relies entirely on the right-hand side of the assignment to guess the type. null is a special literal in Java that represents the absence of an object; it has no specific type. Therefore, the compiler has absolutely no idea if x is supposed to be a String, a User, or a Connection. You must provide an explicit type if you want to initialize a variable to null.