var: local type inference
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)In Map<String, List<Student>> result = new HashMap<String, List<Student>>(); the type is written twice. The compiler already knows it.
var (Java 10) for local variables
var lets the compiler work out a local variable's type from its starting value; the variable still has one fixed type.
Since Java 10, you can write var in place of the type when you declare a local variable, a variable inside a method, with a starting value. The compiler looks at the value on the right side and uses its type.
Example 1 · var infers the type once, and it stays fixed
import java.util.ArrayList;
public class VarBasicsDemo { public static void main(String[] args) { var city = "Mysuru"; var marks = 87; var total = 87L; var fee = 1250.0; var toppers = new ArrayList<String>(); toppers.add("Nikhil"); toppers.add("Farah");
System.out.println(city + " has " + city.length() + " letters"); System.out.println("marks + 1 = " + (marks + 1)); System.out.println("total is a long: " + (total * 1_000_000_000)); System.out.println("fee / 2 = " + (fee / 2)); System.out.println("toppers: " + toppers + ", first is " + toppers.get(0).toUpperCase());
// marks = "ninety"; // compile error: incompatible types, marks is an int }}Mysuru has 6 letters marks + 1 = 88 total is a long: 87000000000 fee / 2 = 625.0 toppers: [Nikhil, Farah], first is NIKHIL
What this code does
- Each variable gets the type of its starting value:
String,int,long,doubleandArrayList<String>. Becausetoppersknows it holdsStrings,get(0).toUpperCase()compiles. 87Lmakestotalalong, so multiplying by a billion does not overflow. The commented line shows that the type is fixed:varis not dynamic typing.
var count = 0; gives an int, var price = 99.5; a double, and var names = new ArrayList<String>(); an ArrayList<String>.
var does not make Java a loosely typed language. The type is decided once, at compile time, and never changes. After var count = 0;, the line count = "ten"; is still a compile error, exactly as with int count = 0;.
The compiled program is the same as if you had written the type. var only changes what you type and what the reader sees.
var marks = 87;→intvar total = 87L;→long(theLdecides)var fee = 1250.0;→doublevar name = student.getName();→ whatevergetName()returns
Where it helps: long generic types and for loops
Generic types can get long: Map<String, List<Integer>> marksBySubject = new TreeMap<String, List<Integer>>(); says the type twice. var marksBySubject = new TreeMap<String, List<Integer>>(); says it once, and the line still shows exactly what the object is.
Example 2 · Where var helps: long generic types and loops
import java.util.List;import java.util.TreeMap;
public class VarGenericsDemo { public static void main(String[] args) { // without var: Map<String, List<Integer>> marksBySubject = new TreeMap<String, List<Integer>>(); var marksBySubject = new TreeMap<String, List<Integer>>(); marksBySubject.put("Physics", List.of(72, 85, 64)); marksBySubject.put("Maths", List.of(91, 78, 88)); marksBySubject.put("Chemistry", List.of(55, 69, 80));
// without var: for (Map.Entry<String, List<Integer>> entry : marksBySubject.entrySet()) for (var entry : marksBySubject.entrySet()) { var sum = 0; for (var m : entry.getValue()) { sum += m; } var average = (double) sum / entry.getValue().size(); System.out.printf("%-10s average %.1f%n", entry.getKey(), average); } }}Chemistry average 68.0 Maths average 85.7 Physics average 73.7
What this code does
- The map's full type is written once, on the right side, and the
forloop needs noMap.Entry<String, List<Integer>>. ATreeMapkeeps subjects in A to Z order. var sum = 0is anint, so the cast(double) sumis still needed before dividing.varcopies the type of the value exactly; it never widens it for you.
Loops are the other big win. for (Map.Entry<String, List<Integer>> e : marksBySubject.entrySet()) becomes for (var e : marksBySubject.entrySet()). The name e and the call entrySet() already tell the reader what it is. Index loops work too: for (var i = 0; i < n; i++). The rule of thumb: use var when the type is obvious from the right side, a new expression, a literal, or a well-named method, and the variable name says the rest.
Where it hides meaning
var result = service.process(); compiles, but what is result? A number, a list, an Optional? The reader must open another file to find out. When the right side does not show the type, write the type.
Example 3 · Trap: the empty diamond gives ArrayList<Object>
import java.util.ArrayList;
public class VarDiamondTrapDemo { public static void main(String[] args) { var subjects = new ArrayList<>(); subjects.add("Maths"); subjects.add("Physics"); System.out.println(subjects.get(0).length()); }}VarDiamondTrapDemo.java:8: error: cannot find symbol
System.out.println(subjects.get(0).length());
^
symbol: method length()
location: class Object
1 errorWhat this code does
- With nothing inside
<>and no declared type on the left, Java has no element type to use, so it picksObject.subjectsis anArrayList<Object>, andObjecthas nolength()method. - Fix it by naming the element type on one side:
var subjects = new ArrayList<String>();orList<String> subjects = new ArrayList<>();.
Two traps come from the inferred type being more exact or less exact than you expect. var items = new ArrayList<>(); has no type inside the diamond, so Java picks ArrayList<Object>, and items.get(0).length() no longer compiles. And var discount = 10; is an int, so discount = 7.5; fails, and discount / 4 is integer division. Also, var takes the class type, not an interface type. var list = new ArrayList<String>(); is an ArrayList<String>, not a List<String>. That rarely matters for local variables, but it is worth knowing.
var. var x = repo.find(id); hides everything; var student = repo.find(id); hides very little.Rules: where var is not allowed
var works only for local variables that start with a value the compiler can type. Everything else is a compile error.
- No fields, method parameters or return types:
varis for local variables,forloop variables and try-with-resources only. - A starting value is required:
var total;fails with "cannot infer type ... without initializer". - No
nullstart value:var x = null;fails, becausenullhas no useful type. - No lambda or method reference without a target:
var f = () -> 5;fails; writeSupplier<Integer> f = () -> 5;. - No array initializer alone:
var a = {1, 2};fails; writevar a = new int[] {1, 2};. - One variable per line:
var a = 1, b = 2;fails.
Example 4 · Mistake: var where Java cannot infer a type
public class VarRulesErrorDemo { public static void main(String[] args) { var total; var winner = null; var square = (int n) -> n * n; var scores = {90, 75, 60}; }}VarRulesErrorDemo.java:3: error: cannot infer type for local variable total
var total;
^
(cannot use 'var' on variable without initializer)
VarRulesErrorDemo.java:4: error: cannot infer type for local variable winner
var winner = null;
^
(variable initializer is 'null')
VarRulesErrorDemo.java:5: error: cannot infer type for local variable square
var square = (int n) -> n * n;
^
(lambda expression needs an explicit target-type)
VarRulesErrorDemo.java:6: error: cannot infer type for local variable scores
var scores = {90, 75, 60};
^
(array initializer needs an explicit target-type)
4 errorsWhat this code does
- Each line breaks one rule: no starting value, a
nullstart value, a lambda with no target interface, and an array initializer with no array type. In every case the right side does not give the compiler a usable type. - Fixes:
int total = 0;,String winner = null;,IntUnaryOperator square = n -> n * n;,var scores = new int[] {90, 75, 60};. Avarfield would also fail: "'var' is not allowed here".
Fix the error
Fix the var mistakes
Read the real compiler error, then pick the line that fixes it.
Round 1 of 3
A variable is declared first and filled in later.
Error
Rules.java:3: error: cannot infer type for local variable name
var name;
^
(cannot use 'var' on variable without initializer)var in lambda parameters (Java 11)
Lambda parameters already have inferred types: in (a, b) -> a + b Java works out a and b from the target interface. Java 11 also allows (var a, var b) -> a + b, which means exactly the same.
Example 5 · var in lambda parameters (Java 11)
import java.util.List;import java.util.function.BiFunction;
public class VarLambdaDemo { public static void main(String[] args) { BiFunction<Integer, Integer, Integer> add = (var a, var b) -> a + b; System.out.println("Seats booked: " + add.apply(42, 18));
List<String> names = List.of("anil", "bhavna", "chetan"); names.forEach((final var name) -> System.out.println("Hello, " + name.substring(0, 1).toUpperCase() + name.substring(1))); }}Seats booked: 60 Hello, Anil Hello, Bhavna Hello, Chetan
What this code does
(var a, var b) -> a + bmeans the same as(a, b) -> a + b; both parameters areInteger, taken fromBiFunction<Integer, Integer, Integer>.- The reason to use
varhere is the modifier:(final var name)is allowed, while(final name)is not. Annotations on lambda parameters use the same form.
So why write it? Because a type, even var, lets you add modifiers and annotations to the parameter. (final var name) -> ... is allowed, but (final name) -> ... is not. Annotation libraries use the same trick, for example (@NonNull var name) -> .... The rule is all or nothing: either every parameter uses var, or none does. (var a, b) -> and (var a, String b) -> are compile errors.
Next step
Check your understanding
12 quick questions