Video in progress
What does the var keyword do, and when should you not use it?
var (Java 10+) lets the compiler infer a local variable's type from the expression on the right. The type is still static and doesn't change; it only shortens the code. When the type isn't obvious from the expression, it makes the code harder to read.
📖 Answer
var users = new HashMap<String, List<User>>(); // the type is obvious
for (var entry : users.entrySet()) { ... }
var result = service.process(data); // what type is result? you can't tell from the code
The rules:
- only for local variables,
forloops and lambda parameters (Java 11+); not for fields, method parameters or return types; - an initial value is required:
var x;is an error; var x = null;is an error, because the type can't be inferred.
The traps:
var list = new ArrayList<>(); // ends up as ArrayList<Object>
var n = 10; // int, not long
This is what I usually do: use var when the type is plainly visible on the right side (new, or a factory method name that tells you the type); where it's the result of a method call and the type matters, write the type. When you use var, the variable name becomes even more important.
Sign up to mark studied questions and save your progress.