Local Variable Type Inference with var
Since Java 10, a local variable can be declared with var, and the compiler works out its type from the initializer. It removes repetition such as Map
Contents
What var does
varvar names = new ArrayList<String>();ArrayList<String>Stringint
varvarvar
| Place | Allowed? | Since |
|---|---|---|
| Local variables with an initializer | Yes | Java 10 |
Loop variables: for (var i = 0; ...)for (var x : items) | Yes | Java 10 |
| try-with-resources variables | Yes | Java 10 |
Lambda parameters: (var a, var b) -> ... | Yes | Java 11 |
| Fields, method parameters, return types | No | |
Variables without an initializer, or initialized with null | No |
What var infers
The program declares variables with var
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class VarBasics {
public static void main(String[] args) {
var count = 10; // int
var price = 9.99; // double
var name = "Ada"; // String
var names = new ArrayList<String>(); // ArrayList<String>, not List<String>
names.add(name);
// Long generic types are where var helps most
var groups = new HashMap<String, List<Integer>>();
groups.computeIfAbsent("even", k -> new ArrayList<>()).add(2);
for (var entry : groups.entrySet()) { // Map.Entry<String, List<Integer>>
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
// The inferred types (primitives show up boxed here, inside an Object[])
Object[] values = {count, price, name, names};
for (Object v : values) {
System.out.println(v + " -> " + v.getClass().getSimpleName());
}
// var is still static typing: the type is fixed at compile time
// count = "ten"; would not compile: count is an int
// A diamond with var infers Object: usually not what you want
var mystery = new ArrayList<>();
mystery.add("x");
mystery.add(1);
System.out.println("new ArrayList<>() with var holds anything: " + mystery);
// Literal suffixes matter
var big = 3000000000L; // long; without L this would not compile
var ratio = 1.5f; // float
Map<String, Object> types = Map.of("big", big, "ratio", ratio);
System.out.println(types.get("big").getClass().getSimpleName() + ", "
+ types.get("ratio").getClass().getSimpleName());
}
}
Output:
even -> [2]
10 -> Integer
9.99 -> Double
Ada -> String
[Ada] -> ArrayList
new ArrayList<>() with var holds anything: [x, 1]
Long, Float
gives10 ,int gives9.99 anddouble gives"Ada" . They print asString andInteger only because they were boxed into anDouble to callObject[] .getClass()- The biggest win is long generic types:
, and the loop variablevar groups = new HashMap<String, List<Integer>>() is avar entry that nobody had to type.Map.Entry<String, List<Integer>> has nothing to infer the element type from, so it becomesvar mystery = new ArrayList<>() and accepted both a string and a number. WithArrayList<Object> , put the type argument on the right:var .new ArrayList<String>()- Literal suffixes decide the type:
is a3000000000L andlong a1.5f .float
Where var is not allowed, and proof that nothing changes at run time
The program compiles code that uses varvarvar
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import javax.tools.ToolProvider;
// Compiles var in places where it is and is not allowed, and checks the bytecode
public class WhereVarWorks {
static final String NOT_ALLOWED = """
import java.util.function.Supplier;
class NotAllowed {
var field = 1; // fields
var method() { return 1; } // return types
void param(var x) { } // method parameters
void several() {
var a = 1, b = 2; // several variables at once
}
}
""";
static final String NO_TYPE = """
class NoType {
void locals() {
var noInit; // no initializer
var nothing = null; // null has no type to infer
var array = {1, 2}; // an array initializer alone
var lambda = () -> 1; // a lambda needs a target type
}
}
""";
static final String EXPLICIT = """
import java.util.ArrayList;
class Same {
int run() {
ArrayList<String> list = new ArrayList<String>();
list.add("x");
String var = "var is not a keyword";
return list.size() + var.length();
}
}
""";
static final String WITH_VAR = EXPLICIT
.replace("ArrayList<String> list =", "var list =")
.replace("String var =", "var var =");
public static void main(String[] args) throws IOException {
Path dir = Files.createTempDirectory("var");
for (String[] src : new String[][] {{"NotAllowed.java", NOT_ALLOWED},
{"NoType.java", NO_TYPE}}) {
compile(dir, src[0], src[1]).lines()
.filter(l -> l.startsWith(dir.toString()))
.map(l -> l.substring(dir.toString().length() + 1))
.forEach(System.out::println);
}
Path a = Files.createDirectories(dir.resolve("a"));
Path b = Files.createDirectories(dir.resolve("b"));
compile(a, "Same.java", EXPLICIT);
compile(b, "Same.java", WITH_VAR);
byte[] explicit = Files.readAllBytes(a.resolve("Same.class"));
byte[] inferred = Files.readAllBytes(b.resolve("Same.class"));
System.out.println("explicit types and var compile to identical class files: "
+ Arrays.equals(explicit, inferred) + " (" + explicit.length + " bytes)");
}
static String compile(Path dir, String name, String code) throws IOException {
Path file = dir.resolve(name);
Files.writeString(file, code);
ByteArrayOutputStream err = new ByteArrayOutputStream();
ToolProvider.getSystemJavaCompiler().run(null, null,
new PrintStream(err, true, StandardCharsets.UTF_8),
"-d", dir.toString(), file.toString());
return err.toString(StandardCharsets.UTF_8);
}
}
Output:
NotAllowed.java:4: error: 'var' is not allowed here
NotAllowed.java:5: error: 'var' is not allowed here
NotAllowed.java:6: error: 'var' is not allowed here
NotAllowed.java:8: error: 'var' is not allowed in a compound declaration
NoType.java:3: error: cannot infer type for local variable noInit
NoType.java:4: error: cannot infer type for local variable nothing
NoType.java:5: error: cannot infer type for local variable array
NoType.java:6: error: cannot infer type for local variable lambda
explicit types and var compile to identical class files: true (433 bytes)
- Fields, return types and method parameters (lines 4 to 6 of
) cannot useNotAllowed : they are part of a class's API, and their types should be stated, not inferred from an implementation detail. Several variables in one declaration are not allowed either.var - The four local variables in
failed with "cannot infer type": there is no initializer,NoType has no useful type,null needs a declared array type, and a lambda needs a target interface to know what it implements.{1, 2} - The two class files were identical:
exists only in the source. There is no run-time cost or difference of any kind.var
var in lambdas, loops and with anonymous classes
The program uses varforvar
import java.util.List;
import java.util.function.BiFunction;
public class VarInLambdas {
@interface NonNull {
}
public static void main(String[] args) {
// Java 11: var in lambda parameters, which allows annotations on them
BiFunction<Integer, Integer, Integer> add = (@NonNull var a, @NonNull var b) -> a + b;
System.out.println("add: " + add.apply(2, 3));
// var in for loops
for (var i = 0; i < 2; i++) {
System.out.print("i=" + i + " ");
}
System.out.println();
// An anonymous class type can only be held by var, which keeps its extra members
var point = new Object() {
int x = 3;
int y = 4;
};
System.out.println("anonymous fields via var: " + (point.x + point.y));
List<String> words = List.of("alpha", "beta");
for (var w : words) {
System.out.println(w.toUpperCase());
}
}
}
Output:
add: 5
i=0 i=1
anonymous fields via var: 7
ALPHA
BETA
- Lambda parameters can already omit their types, so
adds nothing on its own. Its purpose (Java 11, JEP 323) is to allow annotations or(var a, var b) on the parameters, which need a type position to attach to. All parameters must then usefinal .var keeps the anonymous class type, sovar point = new Object() { int x = 3; int y = 4; } compiles. Withpoint.x the fields would be unreachable. It is a curiosity rather than a recommended technique; a local record is clearer.Object point = ...
Where the inferred type comes from
The inferred type is always the static type of the initializer expression, the type the compiler sees, never the class of the object at run time. That rule explains several results that surprise people. The program uses overloaded methods, which are chosen by static type, to reveal what var
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
public class InferenceSource {
static List<String> loadNames() { // declared to return List
return new ArrayList<>(List.of("Ada", "Linus"));
}
// Overloads are chosen by static type, so they reveal what var inferred
static String staticType(List<String> list) {
return "List<String>";
}
static String staticType(ArrayList<String> list) {
return "ArrayList<String>";
}
public static void main(String[] args) {
// 1. var uses the STATIC type of the expression, not the runtime class
var names = loadNames();
var created = new ArrayList<String>();
System.out.println("var names = loadNames(): runtime class "
+ names.getClass().getSimpleName() + ", static type " + staticType(names));
System.out.println("var created = new ArrayList<String>(): static type "
+ staticType(created));
// 2. Mixed numeric operands widen: int and long make a long
int small = 5;
long large = 5000000000L;
var mixed = true ? small : large;
System.out.println("true ? int : long is " + ((Object) mixed).getClass().getSimpleName()
+ " " + mixed);
// 3. A loop counter inferred from 0 is an int, even if the bound is a long
long limit = Integer.MAX_VALUE + 3L;
long steps = 0;
for (var i = Integer.MAX_VALUE - 1; i < limit; i++) { // i is an int
if (++steps > 4) {
System.out.println("int counter wrapped to " + i + "; stopped after " + steps);
break;
}
}
// 4. Lambdas and method references need a target type: give it with a cast
var length = (Function<String, Integer>) String::length;
System.out.println("length of \"varargs\": " + length.apply("varargs"));
}
}
Output:
var names = loadNames(): runtime class ArrayList, static type List<String>
var created = new ArrayList<String>(): static type ArrayList<String>
true ? int : long is Long 5
int counter wrapped to -2147483646; stopped after 5
length of "varargs": 7
is declared to returnloadNames() , soList<String> is avar names , even though the object is anList<String> .ArrayList , on the other hand, is anvar created = new ArrayList<String>() , because that is the type of a constructor call. The overload chosen for each shows the difference.ArrayList<String>- A conditional with an
and aint branch has typelong , solong is amixed even though thelong branch was taken.int madefor (var i = Integer.MAX_VALUE - 1; i < limit; i++) ani , because its initializer is anint ; theint bound does not matter. The counter wrapped around to a negative number, and without the safety stop the loop would never end. Writelong (orlong i ) when the bound is avar i = 0L .long- A method reference or lambda has no type of its own, so
does not compile. A cast supplies the target type, but at that point declaringvar f = String::length is clearer.Function<String, Integer> f
Pitfalls: what var infers that you might not expect
Each case in this program compiles and runs, and each infers a type that differs from what a reader might assume.
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class VarPitfalls {
@SuppressWarnings("lossy-conversions") // the lossy += below is the point of the demo
public static void main(String[] args) {
// 1. The type comes from the initializer: 0 makes an int, and += hides a cast
var total = 0;
for (double price : new double[] {0.99, 1.49, 2.75}) {
total += price; // compiles: total = (int) (total + price)
}
System.out.println("total of 0.99 + 1.49 + 2.75 with var total = 0: " + total);
// 2. var takes the concrete class, not the interface
var names = new ArrayList<String>(); // ArrayList<String>
List<String> declared = new ArrayList<>(); // List<String>
declared = List.of("can switch implementations");
// names = List.of("x"); would not compile: not an ArrayList
System.out.println("declared List reassigned: " + declared + "; names stays "
+ names.getClass().getSimpleName());
// 3. char arithmetic produces an int
var next = 'a' + 1;
System.out.println("var next = 'a' + 1 is " + next + " ("
+ ((Object) next).getClass().getSimpleName() + ")");
// 4. A conditional can infer a type you would never write
boolean ordered = true;
var items = ordered ? List.of(3, 1, 2) : Set.of(3, 1, 2);
System.out.println("inferred a common supertype of List and Set: size " + items.size()
+ ", contains 2: " + items.contains(2));
}
}
Output:
total of 0.99 + 1.49 + 2.75 with var total = 0: 3
declared List reassigned: [can switch implementations]; names stays ArrayList
var next = 'a' + 1 is 98 (Integer)
inferred a common supertype of List and Set: size 3, contains 2: true
madevar total = 0 antotal , andint silently cast each sum back tototal += price , so 0.99 + 1.49 + 2.75 gave 3 instead of 5.23. JDK 20 added the javac warningint for exactly this ("implicit cast from double to int in compound assignment is possibly lossy"); the program suppresses it to show the bug. Write-Xlint:lossy-conversions , or declarevar total = 0.0 .double total has typevar names = new ArrayList<String>() , notArrayList<String> , so it cannot later be assigned aList<String> or aList.of(...) . For local variables this rarely matters; it is one reasonLinkedList is not allowed for fields.var is anvar next = 'a' + 1 (98), becauseint arithmetic is done inchar .int- A conditional between a
and aList inferred their common supertype, an intersection ofSet and other interfaces that cannot even be written in Java. It works, but a reader cannot tell what the type is.Collection
When to use var
The OpenJDK project published style guidelines for varvar
| Good use | Avoid |
|---|---|
var users = new HashMap<String, List<User>>(); | var result = service.process(input); |
for (var entry : map.entrySet()) | var list = new ArrayList<>();ArrayList<Object> |
try (var in = Files.newInputStream(path)) | var total = 0; |
| Intermediate values with clear names in long chains | Short names such as var x |
| Local variables with a small scope | Variables used far from their declaration |
var