☕ Java Advanced

What is the var keyword in Java?

Why Interviewers Ask This

Advanced questions like this reveal whether a candidate has internalized Java deeply enough to make architectural decisions. Strong answers demonstrate both breadth and depth of experience.

Answer

The var keyword (Java 10) enables local variable type inference — the compiler infers the type from the initializer expression, so you do not need to repeat the type. var list = new ArrayList<String>(); is equivalent to ArrayList<String> list = new ArrayList<String>();. var only works for local variables with initializers — it cannot be used for fields, method parameters, return types, or without an initializer. The inferred type is the static type at compile time, so it is just syntactic sugar — not dynamic typing. Use var to reduce verbosity especially with complex generic types, but avoid it when the type would not be obvious to a reader without knowing the right-hand side.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Java codebase.