Skip to main content
PreparationZone Logo
PreparationZone
Back to Java

Java · Medium · Free

var limitations — no fields, no method params, lambda pitfalls?

JavaJava 17+Fresher
Model answer

Local variable type inference

var infers type from initializer—local variables only. Improves readability for verbose generic types but hurts clarity if overused.

  • Not for fields, method parameters, or constructor parameters.
  • Cannot use without initializer—compiler needs type source.
  • Lambdas: var x = (String s) -> s.length() illegal—use explicit param types.
  • Avoid var when type carries domain meaning obscured.
java
var users = new ArrayList<User>(); // ArrayList, not List
List<User> view = users; // widen when passing API
Style guide: var ok when RHS spells type clearly—var file = Path.of(...).