Local type inference with var in Java
var infers the type at compile time; still statically typed; where it is not allowed.
var x = 5; then x = "hello"; In JavaScript that's fine. In Java? Let's find out whether var makes Java dynamic.The compiler fills in the type
Since Java 10, var tells the compiler: "infer this local variable's type from its initializer." Less typing, same type safety.
var count = 5; // int
var name = "Ada"; // String
var list = new ArrayList<String>();Inferred once, fixed forever
The type is decided at compile time and never changes. Java stays statically typed: var x = 5; makes x an int, exactly as if you had written int.
Your turn
What happens?
var x = 5;
x = "hello";
System.out.println(x);hello5Compile error
Show the answer
Compile error. x was inferred as int on the first line, and a String can never go into an int. var is not dynamic typing.
Your turn
What does this print?
var total = 7;
var each = total / 2;
System.out.println(each);3.533.0
Show the answer
total is inferred as int, so total / 2 is integer division and each is the int 3. Want 3.5? Write var total = 7.0;.
var needs something to infer from
Without an initializer there's nothing to infer, so var count; doesn't compile. null alone has no useful type either, so var x = null; fails too ("variable initializer is 'null'").
var count; // error
var nothing = null; // errorWhere var is allowed
Only in local spots: local variables with an initializer, for-loop variables, and lambda parameters (Java 11). Not fields, method parameters or return types: those are part of a class's API and must be written out.
for (var n : names) { } // ok
class Shop {
var total = 0; // error: field
}In real projects
Teams use var to cut noise like Map<String, List<Order>> map = new HashMap<>();, but avoid it when the type isn't obvious, as in var x = service.process();. Readability wins.
Key takeaways
- var x = 5; → x is an int, forever
- Needs an initializer; var x = null; doesn't compile
- Allowed: locals, for loops, lambda params (Java 11)
- Not allowed: fields, method params, return types
With var you can hold an object whose type has no name: var p = new Object() { int x = 5; }; and then p.x works. With a declared type of Object, it wouldn't.
Practice questions
What does this print?
var price = 10;
var total = price / 4;
System.out.println(total);- 2
- 2.5
- 2.0
- Compile error
Check your answer
2. price is inferred as int, so price / 4 is integer division and total is an int with value 2.
Which line does NOT compile?
- var name = "Ada";
- var count;
- var list = new ArrayList<String>();
- var ratio = 0.5;
Check your answer
var count;. var needs an initializer to infer the type from. var count; has nothing to infer, so it's rejected.