Q61: What is Local Variable Type Inference (var in Java 10) and its restrictions?

var allows the compiler to infer local variable types from initializer expressions at compile time. Static typing is preserved.

  • Restrictions:
    • Allowed ONLY for local variables with initializers.
    • CANNOT be used for class fields, method parameter signatures, or return types.
    • CANNOT be initialized to null or array initializers without explicit types (var x = null is illegal).
Valid vs Invalid var Declarations
// Valid
var list = new ArrayList<String>(); // Inferred as ArrayList<String>
var stream = list.stream();

// Invalid / Compile Error
var x; // Error: Needs initializer
var y = null; // Error: Cannot infer type from null
💡 var requires explicit local initializers to determine variable types at compile time.
Key Takeaways
  • var is strictly local type inference at compile time.
  • Illegal on class instance fields, method parameters, or null initializations.
Knowledge Check

Can var be used to declare instance variables (fields) inside a class definition?