Java / Java 21 Interview Questions
What is 'var' in Java and what are its limitations?
var (JEP 286, Java 10) introduces local variable type inference. The compiler infers the type from the initialiser on the right-hand side; you do not need to write the type explicitly. It is not a dynamic type — the variable is still strongly typed at compile time; var is just syntactic sugar.
// Without var
Map> scores = new HashMap>();
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
// With var — type inferred from the right-hand side
var scores = new HashMap>(); // Map>
var reader = new BufferedReader(new FileReader("file.txt")); // BufferedReader
// Works in for-loops
for (var entry : scores.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Works with try-with-resources
try (var in = new FileInputStream("data.bin")) { ... }
// CANNOT be used:
// var x; // no initialiser — type unknown
// var x = null; // null has no type
// private var name; // instance/static fields
// public var foo() { } // return types
// void bar(var x) { } // method parameters
// var x = { 1, 2, 3 }; // array initialiser without explicit type In Java 11, var was extended to lambda parameters so you can add annotations: (var x, var y) -> x + y is equivalent to (x, y) -> x + y but allows (@NotNull var x, @NotNull var y) -> x + y.
More Related questions...