library
beginnerLocal Variable Type Inference (var)
Use var for local variables where the type is obvious, and know when NOT to use it.
var (Java 10) lets the compiler infer the type of a local variable from its initializer. The variable is still statically typed — it's not dynamic typing.
var = 'you know what I mean.' When someone hands you a coffee (new Coffee()), you don't need to announce 'I am now holding a Coffee' — it's obvious.
Key Concepts
1
var list = new ArrayList<String>(); // inferred as ArrayList<String>
var stream = list.stream(); // inferred as Stream<String>
2
Where var can be used:
- Local variables with initializers
- For-each loop variables: for (var item : list)
- For loop indexes: for (var i = 0; i < 10; i++)
- try-with-resources: try (var conn = getConnection())
- Lambda parameters (Java 11): (var x, var y) -> x + y (allows annotations on lambda params)
3
Where var CANNOT be used:
- Method parameters
- Method return types
- Fields (instance or static)
- Without an initializer: var x; is illegal
- With null initializer: var x = null; is illegal (can't infer type)
- Array initializer: var arr = {1, 2, 3}; is illegal
4
Style guidelines:
- Use var when the type is obvious from the right side: var map = new HashMap<String, List<Integer>>()
- Don't use var when it obscures the type: var result = service.process() — what type is result?
- Use var to reduce noise with generics: var entry : entrySet() instead of Map.Entry<String, Integer>