Sub topic 13
When to Use var and When Not To
This chapter covers judgment, not syntax. It assumes you have read the earlier chapters on how var infers types, where it is allowed, and how it interacts with literals, generics and polymorphism. You should be comfortable with local variables, the diamond operator, enhanced for loops and try-with-resources.
The Question to Ask
var never changes what the compiler checks. The variable has the same static type as the initializer, and every later use is checked against it. What changes is what a human reader sees. The explicit type name in String name = ... carries information. With var, that information must come from somewhere else on the line or nearby.
So the test is not "does this compile?" It is "can a reviewer reading only this diff tell the type without opening an IDE?" Code is read in code review, in diffs and on web pages, where no hover tooltip exists.
Cases Where var Helps
The type is already on the right side
When the initializer names the type, the left side repeats it. var removes the repetition and loses nothing.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GoodVar {
public static void main(String[] args) {
// Verbose: the type appears twice
Map<Integer, List<String>> verbose = new HashMap<Integer, List<String>>();
// Same information, written once
var byLength = new HashMap<Integer, List<String>>();
byLength.computeIfAbsent(3, k -> new ArrayList<>()).add("Ada");
byLength.computeIfAbsent(5, k -> new ArrayList<>()).add("Grace");
for (var entry : byLength.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
System.out.println(verbose.size());
}
}The same applies to casts and factory methods whose names state the result, such as var path = Path.of("data.txt"); or var in = new FileInputStream(file);.
The explicit type is long and adds noise
Loop variables over map entries are the usual case. Map.Entry<String, List<Integer>> entry says little that the surrounding code does not already say. If the collection is named well, var entry is clear.
Try-with-resources and short-lived locals
A resource such as var reader = new BufferedReader(...) is used inside a small block. The type is visible in the same line, and the variable's scope is a few lines. This is the ideal profile for var.
Intermediate values in a stream or builder chain
When you split a long chain to name a step, the type of the intermediate value often adds no meaning. The variable name carries the meaning:
import java.util.List;
import java.util.stream.Collectors;
public class StreamSteps {
public static void main(String[] args) {
var names = List.of("ada", "grace", "alan", "barbara");
var longNames = names.stream()
.filter(n -> n.length() > 4)
.collect(Collectors.toList());
System.out.println(longNames); // [grace, barbara]
}
}Cases Where var Hurts
A method call hides the type
var result = service.process(input); // what is result?Nothing on this line says whether result is a Report, a Optional<Report>, a boolean or a List. A reader must look up process. Use the explicit type, or rename the method so the name implies the result.
Numeric inference surprises
Literals default to int and double. Arithmetic follows normal Java rules, so var can hide a precision mistake that an explicit type would have exposed.
public class Pitfalls {
static long total() { return 5_000_000_000L; }
public static void main(String[] args) {
var ratio = 7 / 2; // int, value 3
var half = 7 / 2.0; // double, value 3.5
var big = total(); // long, because total() returns long
var count = 0; // int
count += 2.5; // compiles: compound assignment casts back to int
// count = 2.5; // would not compile: double to int
System.out.println(ratio + " " + half + " " + big + " " + count);
// 3 3.5 5000000000 2
}
}The count += 2.5 line is ordinary Java behavior, but it is easy to miss when you wanted a double accumulator. Write double count = 0; when the intended type is not int. Likewise, use 1L, 1.5f or a cast when a literal must be long, float, byte or short.
The diamond with no target type
var loose = new ArrayList<>(); gives an ArrayList<Object>. It compiles, and it accepts anything, which is almost never what you meant. Either write the type argument (new ArrayList<String>()) or declare the variable with its full type and keep the diamond on the right.
You lose the interface type
An explicit declaration states how you intend to use an object. var states the concrete class.
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class InterfaceLoss {
public static void main(String[] args) {
List<String> a = new ArrayList<>();
a = new LinkedList<>(); // fine: both are Lists
var b = new ArrayList<String>();
// b = new LinkedList<String>(); // does not compile: b is ArrayList<String>
b.add("x");
System.out.println(a.size() + " " + b.size());
}
}If the variable may later hold a different implementation, or you want to stop yourself from using methods outside the interface, declare the interface type. This matters less for locals than for fields and parameters, where var is not allowed anyway. Even so, List<String> names = new ArrayList<>(); documents intent that var cannot.
A refactor silently changes the type
If var x = compute(); is written and compute() later changes from int to long or from List to Set, the variable follows. Usually that is a benefit. When x then flows into code that required int, the compile error appears at the use site, not at the declaration, and the error message can be far from the cause.
Naming Carries the Weight
When the type is no longer written, the variable name must do more work. Compare:
var d = get(); // unclear
var data = get(); // still unclear
var customerOrders = ordersFor(customerId); // plural noun hints at a collection of orders
var elapsedMillis = end - start; // unit stated in the nameA useful rule: if you would not understand the line after replacing var with a blank, improve the name or the initializer before blaming the keyword. Encode units, collection-ness and role in the name instead of using Hungarian-style prefixes.
Scope Is the Safety Net
The shorter the distance between declaration and last use, the safer var is. A 5-line block where the initializer sits next to every use needs no type annotation. A variable declared at the top of a 60-line method and used at the bottom does. Long methods are a problem on their own, but var makes them harder to read.
A Decision Flow
Style Rules Teams Commonly Adopt
Oracle's style guidelines for local variable type inference and most team conventions reduce to a short list:
- Choose variable names that provide useful information.
- Minimize the scope of local variables.
- Consider
varwhen the initializer provides enough information to the reader. - Use
varto break up chained or nested expressions into named steps. - Do not worry about "programming to the interface" for locals, but do not use
varif you rely on the interface type. - Take care with
varand the diamond, and with literals where the inferred type may differ from your intent. - Do not use
varwith a method call whose return type the reader cannot guess.
Agree on these in a style guide or linter configuration rather than arguing case by case in reviews. A consistent rule such as "never var on method-call initializers unless the method name states the type" is easy to check.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Collection accepts any element type | `var x = new ArrayList<>();` infers `ArrayList<Object>` | Write the type argument: `new ArrayList<String>()` |
| Integer division gives the wrong result | `var r = a / b;` with both `int` | Cast or use a `double` operand |
| Cannot assign a different implementation | `var` captured the concrete class | Declare the interface type explicitly |
| Reviewer cannot tell what a variable holds | Method call initializer, vague name | Explicit type or a clearer name |
| `var x = null;` or `var y;` will not compile | No usable type to infer | Declare an explicit type |
Applying the Rules to Real Code
Consider this method and the choices a careful reviewer would make:
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.util.List;
public class Review {
public static void main(String[] args) throws IOException {
var path = Path.of("notes.txt"); // type named by the factory: good
Files.writeString(path, "one\ntwo\nthree\n");
List<String> lines = Files.readAllLines(path); // keep: readers should see a List
var lineCount = lines.size(); // int, the name says "count"
for (var line : lines) { // short scope, element type is clear
System.out.println(line);
}
System.out.println(lineCount);
}
}var path is justified by Path.of. lines keeps its explicit type, because readAllLines does not name its result and the type is part of the story. var lineCount is a judgment call. Some teams prefer int, and both are defensible if applied consistently.
Exercises
Exercise
Which of these declarations is the weakest use of var, and how would you fix it? (a) var names = new ArrayList<String>(); (b) var conn = dataSource.connect(); (c) var path = Path.of("a.txt");
Show answer
(b). The method call connect() does not say what type it returns, so a reader must look it up. Write the explicit type (for example Connection conn = dataSource.connect();) or use a name that makes the type clear. (a) and (c) show the type in the initializer.
Exercise
What is the type and value of total after this code runs, and what would you change if you wanted 2.5? var total = 0; total += 2.5;
Show answer
total is an int with the value 2, because compound assignment casts the result back to int. Declare it as double total = 0; (or var total = 0.0;) to keep 2.5.
Exercise
You write var items = new ArrayList<String>(); and later try items = new LinkedList<String>();. Why does this fail, and how do you allow both?
Show answer
var infers ArrayList<String>, and a LinkedList is not an ArrayList, so the assignment does not compile. Declare the variable as List<String> items = new ArrayList<>(); so either implementation can be assigned.