Sub topic 4
Where you can use var
This chapter assumes you can write basic Java, know primitive and reference types, and have used enhanced for loops, try-with-resources, and simple lambdas. Earlier chapters covered how var infers a type from an initializer. This chapter maps the places in a program where the compiler accepts var. The next chapter covers the rejected places in detail.
The rule in one sentence
You can write var where Java declares a local variable and that declaration has an initializer the compiler can inspect. A local variable lives inside a block of code: a method, a constructor, an initializer block, a lambda body, or a block inside a switch. The var name never works for members of a class or for anything that forms part of a method's public signature.
The compiler decides by looking at the syntax around the name, so the rule is mechanical. It does not depend on how complicated the initializer is.
The allowed contexts at a glance
| Context | Example | Inferred from |
|---|---|---|
| Local variable in a method, constructor, or initializer block | `var total = 0;` | The initializer |
| Local variable in a nested block, such as a `switch` case | `var label = "x";` | The initializer |
| Basic `for` loop variable | `for (var i = 0; i < n; i++)` | The initializer |
| Enhanced `for` variable | `for (var s : list)` | The element type of the array or `Iterable` |
| try-with-resources variable | `try (var r = open())` | The initializer |
| Lambda parameter | `(var a, var b) -> a + b` | The functional interface's target type |
One program that uses every allowed context
The following program declares a variable with var in each place the table lists. It collects its output in a list so you can see the inferred values at the end.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.BinaryOperator;
public class VarWhere {
private final List<String> log = new ArrayList<>();
{
var marker = "initializer block";
log.add(marker);
}
VarWhere() {
var origin = "constructor";
log.add(origin);
}
void run() throws IOException {
var day = 3;
switch (day) {
case 3 -> {
var label = "midweek";
log.add(label);
}
default -> log.add("other");
}
int[] numbers = {4, 5, 6};
var sum = 0;
for (var n : numbers) {
sum += n;
}
log.add("sum=" + sum);
for (var i = 0L; i < 2; i++) {
log.add("long " + i);
}
for (var entry : Map.of("k", 1).entrySet()) {
log.add(entry.getKey() + "=" + entry.getValue());
}
try (var reader = new BufferedReader(new StringReader("first\nsecond"))) {
log.add(reader.readLine());
}
BinaryOperator<Integer> max = (var a, var b) -> Math.max(a, b);
log.add("max=" + max.apply(7, 9));
System.out.println(log);
}
public static void main(String[] args) throws IOException {
new VarWhere().run();
}
}Running it prints:
[initializer block, constructor, midweek, sum=15, long 0, long 1, k=1, first, max=9]The sections below explain what the compiler infers in each context.
Ordinary local variables
An ordinary local variable is any declaration statement inside a block. var origin = "constructor"; has the type String, and var day = 3; has the type int. Constructors and initializer blocks count as method-like bodies, so var works there. The same goes for static initializer blocks.
Modifiers still apply. You can write final var limit = 5; to forbid reassignment. Without final, you can reassign a var variable, but only with a value that fits the inferred type:
var count = 1;
count = 2; // fine
// count = "two"; // does not compile: String cannot become intA var variable is scoped like any other local variable. It is visible from its declaration to the end of the enclosing block, and a nested block cannot redeclare the same name.
Basic for loops
In for (var i = 0L; i < 2; i++), the initializer 0L is a long, so i is a long. This is a common source of surprises. If you write for (var i = 0; ...) and later compare i with a long bound, that works through promotion. If you write var i = 0 and then try to assign a long to i, it fails.
The loop header may declare only one variable with var. A header such as for (var i = 0, j = 10; i < j; i++, j--) is rejected because var allows only one declarator per statement. Declare int i = 0, j = 10 with explicit types if you need two loop variables.
Enhanced for loops
For for (var x : source), the compiler infers the type of x from the element type of source.
- For an array
int[],xis anint. - For a
List<String>,xis aString. - For a
Map<String, Integer>entrySet(),xis aMap.Entry<String, Integer>.
The Map.Entry case is the best argument for var in loops. The explicit type, Map.Entry<String, Integer>, is long and adds little information, because entrySet() already tells the reader what each element is.
If the source is a raw type such as a plain List, the element type is Object, and var infers Object. This is the same result you get from an explicit declaration, but with var you might not notice it.
try-with-resources
A try-with-resources variable declared with var takes the type of its initializer, as in try (var reader = new BufferedReader(...)). The inferred type is BufferedReader, and it must implement AutoCloseable, like any resource.
Resource variables are implicitly final, so you cannot reassign them inside the try block. This behavior does not change when you use var.
try (var reader = new BufferedReader(new StringReader("data"))) {
// reader = null; // does not compile: resource variables are final
System.out.println(reader.readLine());
}Lambda parameters
A lambda parameter can be declared as var, as in (var a, var b) -> Math.max(a, b). The type of each parameter comes from the lambda's target type. Here the target is BinaryOperator<Integer>, so both parameters are Integer. This is different from every other context, because the lambda has no initializer to infer from. The functional interface supplies the types.
Two rules apply:
- If one parameter uses
var, all of them must.(var a, b) -> a + band(var a, int b) -> a + bdo not compile. - You cannot use
varin a lambda with a single unparenthesized parameter. Write(var a) -> a, notvar a -> a.
The practical reason to write var here is that it lets you add a modifier or annotation to the parameter without spelling out the type, for example (final var a, final var b) -> a + b. A later chapter covers this in full.
Places where var is not allowed
The compiler rejects var wherever a type is part of a declaration that is not a local variable with an initializer. Only the main cases are listed here.
public class VarNotHere {
// var field = 1; // fields
// var compute() { return 1; } // method return types
// void take(var param) { } // method parameters
// var[] items = new String[0]; // var as array element type
// java.util.List<var> list; // var as a type argument
void demo() {
// try { } catch (var e) { } // catch parameters
var ok = new java.util.ArrayList<String>(); // fine
System.out.println(ok.size());
}
}All the commented lines fail for the same reason. A field, a parameter, or a return type is visible outside the method body, and other code compiles against it. If the type came from an initializer buried inside one class, a change to that initializer could silently change the public interface. Local variables have no such effect, because nothing outside the block can see them. The next chapter looks at each rejected case and its compiler message.
Common mistakes
- Expecting a loop variable to be a wider type.
for (var i = 0; ...)givesint. Use0Lor0.0when you needlongordouble. - Using
varwith a raw collection. The elements becomeObject, and you lose the checking you wanted. - Mixing
varand explicit types in lambda parameters. The compiler requires all or none. - Assuming
varmakes a variablefinal. It does not. Only a try-with-resources variable is implicitly final, and that is a rule of try-with-resources. - Putting
varin a field to save typing. It never compiles. Use the explicit type, or keep the value in a local variable.
Exercises
Exercise
Which of these declarations compile? (a) for (var i = 0, j = 5; i < j; i++) {} (b) for (var s : List.of("a", "b")) {} (c) BinaryOperator<Integer> f = (var a, b) -> a + b; (d) try (var r = new StringReader("x")) {}
Show answer
Only (b) and (d) compile. (a) fails because var allows only one declarator per declaration. (c) fails because a lambda cannot mix var and an implicitly typed parameter; all parameters must use var. In (b) s is a String, and in (d) r is a StringReader.
Exercise
Why does class Counter { private var count = 0; } fail to compile, even though var count = 0; works inside a method of the same class?
Show answer
var is allowed only for local variables, lambda parameters, and loop and resource variables. A field is part of the class's structure and may be used by other code, so its type must be written explicitly. A local variable is visible only within its own block, so inferring its type from the initializer cannot affect any other code.
Exercise
In for (var entry : Map.of("k", 1).entrySet()), what is the type of entry, and what is the type of var i = 0L in a basic for loop?
Show answer
entry is Map.Entry<String, Integer>, taken from the element type of the entrySet() collection. i is long, because the literal 0L is a long.