var (local type inference)
var (Java 10+) is a contextual keyword for local variable type inference. Write var x = ... and the compiler figures out x's type from the initialiser. It is not dynamic typing — the type is fixed at compile time, just not written out.
Usage
var name = "Ada"; // String
var age = 36; // int
var list = new ArrayList<String>(); // ArrayList<String>
var now = LocalDateTime.now(); // LocalDateTime
for (var entry : map.entrySet()) { // Map.Entry<K, V>
System.out.println(entry.getKey());
}
try (var reader = Files.newBufferedReader(path)) {
return reader.readLine();
}
Where var is allowed
- Local variables with an initialiser
forloop indices- enhanced-for loop variables
- try-with-resources
- Lambda parameters (since Java 11, only for adding annotations)
Where var is NOT allowed
- Field types (
private var name;— error) - Method parameters or return types
- Without an initialiser (
var x;— error) - With a
nullinitialiser (the compiler cannot infer the type)
Style advice
Use var when the type is obvious from the right-hand side (constructors, factory methods, type-name-as-variable-name patterns). Avoid it when the type is not clear from the initialiser — don't force readers to run the compiler in their head.