Part 02 / Topic 7 of 9
var: local type inference
var tells the compiler "work out the type yourself from the value on the right." It is not dynamic typing: the type is still fixed forever, at compile time — var only saves you from typing it.
var city = "Pune"; // the compiler works out: String
var quantity = 3; // the compiler works out: int
var price = 149.50; // the compiler works out: double
Output (examples/06_var_keyword.java):
Pune
3
149.5
true
448.5
PUNE
Two things var cannot do, both caught at compile time:
var quantity = 3;
quantity = "three";
// error: incompatible types: String cannot be converted to int
var empty;
// error: cannot infer type for local variable empty
// (cannot use 'var' on variable without initializer)
var needs a value to read the type from; it cannot be left empty, and it cannot change type later — it is exactly as strict as writing the type name out, just shorter.
var is a style choice, not a requirement. It reads well when the type is obvious from the right-hand side (var total = quantity * price;) and reads worse when it hides something useful (var result = compute(); — what type is that?). Use plain type names when you are learning; reach for var once the type is genuinely obvious.
Full program: examples/06_var_keyword.java.
Done here? The practice set for Part 2 — including the solutions — is on the part page.