When should you prefer var (local variable type inference) and when should you avoid it?

In Java, the use of the `var` keyword for local variable type inference is a powerful feature introduced in Java 10. It allows developers to declare variables without specifying their types explicitly, letting the compiler infer the type from the assigned value. However, while `var` can enhance code readability and reduce verbosity, there are specific scenarios where its use is more beneficial, and others where it is less suitable.

When to Prefer 'var'

  • Readability: When the type is obvious from the right-hand side of the assignment, using `var` can make the code cleaner.
  • Complex Types: For complex generics or anonymous classes, using `var` can simplify declarations.
  • Local Scope: When a variable is declared within a limited scope (like within a loop), using `var` can streamline your code.

When to Avoid 'var'

  • Ambiguity: If the type isn't clear from the assignment, using `var` can make the code harder to understand.
  • Type Safety: In certain situations where explicit type declarations enhance type safety, avoid using `var`.
  • Public APIs: When exposing types in public APIs, being explicit with types is generally better for documentation and clarity.

Java local variable type inference var keyword coding best practices