Java / Java 21 Coding Standards Interview Questions
Define var and explain the coding standard guidelines around its use in Java 21?
var tells the compiler to infer a local variable's type from the expression on the right-hand side at compile time; it is not a dynamic type and the variable is still statically typed once inferred.
var orders = new ArrayList<Order>(); // inferred as ArrayList<Order>
The standard guideline is to use var only when the type is already obvious from the right-hand side, such as var list = new ArrayList<String>(), or when the exact type does not matter to the reader, such as loop indices in an enhanced for-loop.
var is avoided when the constructor or method call does not make the type clear, for example var result = service.process(order), because the reader would have to open the method signature just to know what result is. It is also restricted to local variables and cannot be used for fields, method parameters, or return types.
More Related questions...