Command Palette

Search for a command to run...

Back to the lesson: Topic 1.11 — Local Variable Type Inference with var
Core Java · Example 5 of 5 Java 11+

var on lambda parameters

Writing (a, b) -> a + b does the same. The var form exists so you can annotate parameters, as in (@Nonnull var a, @Nonnull var b) -> a + b. Either all parameters use var or none do.

Since Java 10 you can write var instead of a local variable's type when the initializer already makes the type obvious. The compiler works out the exact type once, at compile time, and the variable keeps that type forever: Java stays statically typed.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Rewrite this with var wherever the type stays obvious: String city = "Delhi"; int pop = 32; double area = 1484.0; and print pop / area per square km (just the raw division).

02

Use var to build a TreeMap<String, Integer> of three fruits and their prices (apple 120, banana 40, cherry 300), then loop with var over the entries and print each, followed by the total.

03

Show that var keeps the literal's exact type: declare var small = 7; and var large = 7L;, and print small * 1_000_000_000 and large * 1_000_000_000.

Explain it without notes

01

What does var do, and why is Java still statically typed when you use it?

02

List the places where var can't be used and give the reason for two of them.

03

What type does var list = new ArrayList<>(); have, and why is that a problem?

04

When would you choose to write the type instead of var, even though var would compile?

var on lambda parameters Java 11+
Sign in to run this example in your browser.

Expected output

2 + 3 = 5