Which two code fragments compile?
var is legal only for local variables that have an initializer from which the compiler can infer a type. Inferring a superclass type with var x = new A() allows a later assignment of a subclass instance, and var x = new ArrayList<>() infers ArrayList<Object>, so adding both an Integer and a String compiles. In contrast, reassigning a String literal to a variable inferred as int is an incompatible-types error, var cannot be initialized from a bare null, var is not permitted for fields, and redeclaring a method parameter's name as a local variable is a duplicate-variable error.
var
var x = new A()
var x = new ArrayList<>()
ArrayList<Object>
int
null
Community Discussion