Sub topic 13
When to use `var` and when not to
Assume you know basic Java declarations, reference and primitive types, generics, enhanced for loops, try-with-resources, and lambda expressions. This chapter focuses on the design decision: when does var make code easier to read, and when does an explicit type communicate more clearly?
var asks the compiler to infer a local variable's static type from its initializer:
var names = new ArrayList<String>();The variable still has one fixed type. In this example, its type is ArrayList<String>, not a dynamically changing type. Later assignments must be compatible with that type, and the compiler checks every method call at compile time.
Use `var when the initializer explains the type
var works well when the right side makes the type obvious:
var user = new User("Ada");
var retryCount = 3;
var completed = true;
var report = new MonthlyReport();A reader can identify the important type without searching elsewhere. The declaration is shorter, and changing the concrete implementation later may require fewer edits.
It is also useful with long generic types:
var ordersByCustomer = new HashMap<Customer, List<Order>>();Writing the complete type on both sides adds repetition. The initializer already states the type precisely.
Use `var` for local implementation details
A local variable often exists only to make a calculation or sequence of operations readable:
var input = Files.readString(path);
var normalized = input.trim().toLowerCase();
var words = normalized.split("\\s+");The exact inferred types are String, String, and String[]. The names and method calls provide enough context, so repeating those types would not add much information.
var also fits loop variables when the collection clearly determines the element type:
for (var order : orders) {
total += order.amount();
}For try-with-resources, var can keep resource declarations focused:
try (var reader = Files.newBufferedReader(path)) {
System.out.println(reader.readLine());
}Avoid `var when the type carries important meaning
An explicit type is clearer when it documents an abstraction, contract, or design choice:
List<String> names = new ArrayList<>();Here, List<String> tells readers that the code depends on the list interface rather than on ArrayList features. This supports programming to an interface.
Compare these declarations:
List<String> names = new ArrayList<>();
var names = new ArrayList<String>();The first communicates the intended public behavior. The second exposes the concrete implementation type. Neither is always wrong, but they express different decisions.
Use an explicit type when the initializer is complicated or misleading:
Reader reader = createReader(configuration);If createReader returns a type that is difficult to recognize, the declared type can explain how the variable is meant to be used.
| Prefer `var` | Prefer an explicit type |
|---|---|
| The initializer clearly names the type | The abstraction is important |
| The type is long or repetitive | The initializer hides the type |
| The variable is a short-lived local detail | The declaration documents an API boundary |
Watch for inferred types that surprise readers
Literal defaults can produce types different from your intention:
var count = 1; // int
var distance = 1.0; // double
var total = 1L; // longUse a suffix or explicit type when the numeric type matters:
var fileSize = 1L;
float ratio = 1.0f;Generics can also become too broad when the diamond operator has no useful target type:
var values = new ArrayList<>(); // ArrayList<Object>Prefer a type argument in this case:
var values = new ArrayList<String>();The goal is not to remove every explicit type. The goal is to remove repetition while preserving the information a reader needs.
A practical decision process
Before replacing an explicit type with var, ask:
- Can a reader identify the inferred type immediately?
- Does the concrete type matter, or should the code show an interface?
- Could a future change make the initializer less obvious?
- Does the declaration remain clear without navigating to another method?
If the answer to the first question is no, keep the explicit type. Consistency within a codebase also matters. Follow the project's style rules rather than applying var mechanically.
Exercise
Should this declaration use var or an explicit type, and why? List<Path> files = Files.list(directory).toList();
Show answer
Keep the explicit type. It communicates that the code uses the List<Path> abstraction, while the stream-based initializer does not make the complete result type as clear.