local variable type inference

Declaring a local variable with var, so the compiler infers its type from the initializer.

In more detail

var works only for local variables with an initializer, including loop variables and resources in try-with-resources. It cannot be used for fields, method parameters or return types, and var x; or var n = null; do not compile. The inferred type is fixed at compile time; var does not make Java dynamically typed.

Example

var list = new ArrayList<String>(); // ArrayList<String>
// var x;  // does not compile

Related terms

Taught in

References

Certification courses