The initializer decides the type
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.
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).
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.
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
What does var do, and why is Java still statically typed when you use it?
List the places where var can't be used and give the reason for two of them.
What type does var list = new ArrayList<>(); have, and why is that a problem?
When would you choose to write the type instead of var, even though var would compile?
Expected output
count / 4 = 2
price / 4 = 2.5
big + 1 = 3000000001
letter + 1 = 66
name.length = 4
count now = 15