☕ Java Advanced

What is the var keyword in Java?

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.