QuestionQ21

Working with Java Data Types

Which two code fragments compile?

Choose two
  • A
  • B
  • C
  • D
  • E
  • F
Explanation

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.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!