Stop 02 · Variables, Data Types & OperatorsTopics · 2/7

Type Inference with var

Part of the Java Roadmap

In short

Java used to make you write the type twice: ArrayList<String> names = new ArrayList<String>(). Since Java 10, var lets the compiler work out the type for you, without making Java any less strict.

Since Java 10, var lets the compiler infer the type of a local variable from its initial value. The variable is still statically typed; var only saves you from writing the type twice.

The jaadu at a courier counter peeks into a cardboard box full of books and stamps a picture of a book on its side.

Think of it like this

The parcel that labels itself

At a courier counter, the clerk looks at what you hand over and writes "BOOKS" on the box. You did not fill in the label, but the box is still labelled, and nobody can later slip shoes into it. var is that clerk: the compiler reads the value and stamps the type on the variable permanently.

Watch it happen

Explicit type vs var

Explicit type

  • Map<String, List<Integer>> marks = new HashMap<>();
  • Type is visible at a glance
  • Required for fields, parameters and return types

var

  • var marks = new HashMap<String, List<Integer>>();
  • Less repetition on long generic types
  • Only for local variables with an initial value

Both are equally type-safe. Use var when the type is obvious from the right-hand side, and spell it out when it is not.

The big ideas

What you need to know

Still statically typed

var count = 10; makes count an int forever. Assigning "ten" later is a compile error.

Locals only

Works for local variables, for-loop variables and try-with-resources. Not for fields, method parameters or return types.

Needs an initial value

var x; and var y = null; do not compile. The compiler needs something to infer from.

Readability first

var order = new Order(); is clear. var result = process(); hides what result is.

See it in code

Walk through the code

java
1import java.util.ArrayList;2import java.util.HashMap;3 4public class VarDemo {5    public static void main(String[] args) {6        var city = "Hyderabad";              // String7        var population = 10_000_000;         // int8        var cities = new ArrayList<String>(); // ArrayList<String>9        cities.add(city);10 11        var fares = new HashMap<String, Double>();12        fares.put("Metro", 45.0);13 14        for (var entry : fares.entrySet()) {15            System.out.println(entry.getKey() + " costs ₹" + entry.getValue());16        }17        // population = "ten million"; // compile error: int stays int18    }19}

1/4The compiler infers String and int from the values.

var on locals, collections and a for-each loop. Underscores in 10_000_000 are just for readability.

Save yourself the pain

Common mistakes

Oops

var list = new ArrayList<>();

Do this instead

With nothing to infer from, this becomes ArrayList<Object>. Write new ArrayList<String>() when you use var.

Oops

Thinking var makes Java like JavaScript or Python.

Do this instead

The type is fixed at compile time. var only saves typing; it never changes the type later.

Your mission

Rewrite with var

~10 min

Quick check

Where can you use var?

Go deeper

  1. 1Rewrite five local variable declarations with var and check the inferred types in IntelliJ.
  2. 2Try var without an initial value and read the compiler error.
  3. 3Decide when var hurts readability, such as var x = getData(), and avoid it there.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge