Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 201 ยท Variables and Types

Local Variable Type Inference with var

Learn how Java's var keyword infers local variable types, where it is allowed and forbidden, what type it really picks, and when var makes code clearer or harder to read.

Since Java 10, you can declare a local variable with var instead of writing its type. The compiler looks at the value on the right of = and works out the type itself. This is called local variable type inference:

Java
var count = 10;                        // int
var name = "Ada";                      // String
var scores = new ArrayList<Integer>(); // ArrayList<Integer>

var is not a dynamic type, and it doesn't make Java behave like JavaScript or Python. The variable still has one fixed type, decided at compile time, exactly as if you had written it out. var just saves you from typing (and reading) what's already obvious. In this lesson you'll learn exactly what var infers, the places it's allowed, the errors you'll meet, and the judgment calls that separate clean var code from confusing code.

var is still static typing

The most important fact about var: once the compiler has inferred a type, that type is locked in. You can't later store a value of another type:

Java
var total = 0;      // total is an int, forever
total = 42;         // fine
total = "many";     // error: incompatible types: String cannot be converted to int

The generated bytecode is identical whether you write int total = 0; or var total = 0;. There's no runtime cost and no runtime check, because the type exists only at compile time, just like any other declared type.

How can you see the type the compiler chose? IDEs show it when you hover over the variable. In a program, you can let method overloading reveal it: Java picks the overload that matches the variable's static type.

Java Which type did var infer?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The inferred type is simply the type of the expression on the right, following the normal rules from Primitive Data Types and Arithmetic Operators. A literal 42 is an int, so var a = 42; is an int, never a long or byte. If you want another type, say so with a suffix (42L) or write the type explicitly.

var is a reserved type name, not a full keyword. That's why old code that used var as a variable or method name still compiles (var var = "ok"; is legal, though please don't). You can't name a class or interface var, though. See Java Keywords and Identifiers.

Where you can use var

var works only for local variables that are initialized where they're declared. That covers:

  • local variables in methods, constructors and initializer blocks: var total = 0;
  • the index of a classic for loop: for (var i = 0; i < 10; i++)
  • the variable of an enhanced for loop: for (var item : items)
  • resources in try-with-resources: try (var reader = Files.newBufferedReader(path))
  • lambda parameters (Java 11+): (var x, var y) -> x + y

It is not allowed for:

  • fields (instance or static variables)
  • method parameters and return types
  • constructor parameters
  • catch parameters

The reason is deliberate. Fields, parameters and return types form the contract of a class: other code depends on them, so they must be stated clearly. A local variable lives only inside one method, where its initializer is right there to read. In a compact source file this means even "top-level" variables can't use var, because they're fields of the hidden class:

Java var is not allowed on fields (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler answers with error: 'var' is not allowed here. Write int counter = 0; instead.

Errors you'll meet

Because the compiler infers the type only from the initializer, every rule follows from one question: does the initializer, on its own, have a clear type? When it doesn't, you get an error that usually starts with cannot infer type for local variable:

Code Error (the part in parentheses)
var x; cannot use 'var' on variable without initializer
var x = null; variable initializer is 'null'
var a = {1, 2, 3}; array initializer needs an explicit target-type
var f = () -> 42; lambda expression needs an explicit target-type
var m = String::length; method reference needs an explicit target-type
var a = 1, b = 2; 'var' is not allowed in a compound declaration
var[] a = new int[3]; 'var' is not allowed as an element type of an array

Each has a simple fix:

Java
int x;                                  // declare without var if you assign later
String name = null;                     // null has no type of its own
var a = new int[] {1, 2, 3};            // or: int[] a = {1, 2, 3};
Supplier<Integer> f = () -> 42;         // lambdas need a target type
var a = 1;                              // one variable per declaration
var b = 2;
var arr = new int[3];                   // var infers int[] by itself

Lambdas and method references have no type of their own: the same lambda () -> 42 could be a Supplier<Integer>, an IntSupplier or a Callable<Integer>. So they always need a declared target. You'll meet them in Lambda Expressions.

var with generics and the diamond trap

var shines with long generic types, where the type would otherwise be written twice:

Java
Map<String, List<Integer>> scoresByStudent = new HashMap<String, List<Integer>>();   // Java 6 style
Map<String, List<Integer>> scoresByStudent = new HashMap<>();                         // diamond
var scoresByStudent = new HashMap<String, List<Integer>>();                           // var

But don't combine var with the diamond <>. The diamond infers type arguments from the left side, and with var there is no left side. Java falls back to Object:

Java var with generics: right and wrong

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

mixed accepts anything, so the compiler can no longer protect you. The fix is to put the type arguments on the right: new ArrayList<String>(). Notice how var entry saves typing Map.Entry<String, Integer>, a type that adds little for the reader. (Compact source files import all of java.base automatically, which is why ArrayList and HashMap work without import lines here. Maps and their methods are covered in HashMap.)

var infers the concrete type

With an explicit type you often program to an interface: List<String> names = new ArrayList<>();. With var, the type is the class on the right, ArrayList<String>. Inside a short method that rarely matters. It only shows up if you later assign a different implementation, such as a LinkedList, to the same variable, which var won't allow.

var in loops

Loop variables are among the best places for var, because the context almost always makes the type obvious:

Java
for (var i = 0; i < 5; i++) { ... }              // int
for (var name : List.of("Ada", "Alan")) { ... }  // String
for (var entry : map.entrySet()) { ... }         // Map.Entry<K, V>

Watch out with numeric loops, though. var i = 0 is always an int. If the bound is a long beyond the int range, i overflows before reaching it. Write long i = 0 (or var i = 0L) when you mean long.

var for lambda parameters

Since Java 11 you may write var for lambda parameters. Normally you'd just leave the types out, so why bother? Because var lets you attach annotations or the final modifier, which need a type position to attach to:

Java
BiFunction<Integer, Integer, Integer> add = (var a, var b) -> a + b;
BiFunction<String, String, String> join = (final var first, final var second) -> first + " " + second;
// (@NonNull var s) -> s.length()   -- with an annotation library

The rule is all or nothing: either every parameter uses var, or none does. (var a, b) -> a + b and (var a, int b) -> a + b are errors.

Non-denotable types: a var superpower

Occasionally var can hold a type you can't even write. The classic example is an anonymous class with extra members:

Java var keeps the anonymous class type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

If you wrote Object stats = ..., the fields count and sum would be invisible, because Object has no such fields. var keeps the precise anonymous type, so you can use them. It's a neat trick for quick local tallies, though a small record or class is usually clearer in real code.

When var helps and when it hurts

var is a readability tool. Use it when it removes noise, and skip it when it removes information the reader needs.

Good uses, where the type is obvious from the right side:

Java
var reader = new BufferedReader(new InputStreamReader(System.in));
var customers = new ArrayList<Customer>();
var path = Path.of("data", "report.csv");
var matcher = pattern.matcher(input);
for (var entry : inventory.entrySet()) { ... }

Questionable uses, where the reader has to guess:

Java
var result = service.process(order);   // what is result? a boolean? an Invoice?
var data = load();                      // no clue at all
var total = price * quantity;           // int? long? double? depends on two other variables
var x = 0;                              // fine type-wise, but "x" says nothing

Guidelines that most teams agree on:

  • Use var when the initializer names the type: constructors (new Customer()), factory methods like Path.of, and casts.
  • Choose good variable names. With var, the name carries more weight: var unpaidInvoices = findUnpaid(); reads better than var list = findUnpaid();.
  • Keep the scope small. A var declared at the top of a 100-line method forces readers to scroll back. In short methods it's harmless.
  • Be careful with numbers. Mixed arithmetic hides whether the result is int, long or double, and that difference matters for overflow and division.
  • Don't use var with the diamond (new ArrayList<>()), or you get Object type arguments.
  • Follow your team's style. Some codebases use var widely, others only for long generic types. Consistency matters more than either choice.

A good test: cover the right side of the declaration with your hand. If the variable name alone still tells you what kind of value it is, var is fine. If not, write the type or pick a better name.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What type does var amount = 100; give amount?

    The type is inferred once, from the initializer. The literal 100 is an int, so amount is an int for its whole life.
  2. 2. Which declaration compiles?

    An array creation expression with new String[] has a clear type. A bare array initializer, no initializer at all, or null gives the compiler nothing to infer from.
  3. 3. After var list = new ArrayList<>();, what does list.add(42) do?

    With var there's no target type for the diamond, so Java infers ArrayList<Object>, and any object can be added. Write new ArrayList<String>() instead.
  4. 4. Where is var NOT allowed?

    Method parameters, return types and fields are part of a class's contract and must be written explicitly. The other three are all valid places for var.
  5. 5. What happens with var count = 0; count = 2.5;?

    count was inferred as int, and assigning a double to an int is a lossy conversion that needs a cast, so the compiler rejects it.

Summary

  • var lets the compiler infer a local variable's type from its initializer (Java 10+). The type is still fixed at compile time.
  • It works for initialized local variables, for and enhanced-for variables, try-with-resources and lambda parameters, but not fields, parameters, return types or catch parameters.
  • The initializer must have a type on its own: no var x;, = null, bare array initializers, lambdas or method references, and one variable per declaration.
  • var infers the exact type of the expression: 42 is int, new ArrayList<String>() is ArrayList<String>. Avoid var with the diamond <>.
  • var can hold non-denotable types such as anonymous classes with extra fields.
  • Use var when the type is obvious from the right side and the name is descriptive; write the type when it carries information the reader needs.

Next: Constants and final, where you'll make variables that can't change and learn the naming rules for constants.