nerdexam
Oracle

1Z0-829 · Question #39

Which two code fragments compile?

The correct answer is B. class I2 { public void m(int x) { var x = 10; } } E. class I5 { public void m() { var strVar = null; } }. The two code fragments that compile are B and E. These are the only ones that use the correct syntax for declaring and initializing a var variable. The var keyword is a reserved type name that allows the compiler to infer the type of the variable based on the initializer…

Working with Java Objects and Classes

Question

Which two code fragments compile?

Options

  • Aclass I6 { public static void main(String[] args) { var x = new ArrayList<>(); x.add(10); x.add("30"); System.out.println(x); } }
  • Bclass I2 { public void m(int x) { var x = 10; } }
  • Cclass A {} class B extends A {} class I4 { public static void main(String[] args) { var x = new A(); x = new B(); } }
  • Dclass I3 { public static void main(String[] args) { var a = 10; a = "30"; } }
  • Eclass I5 { public void m() { var strVar = null; } }

How the community answered

(53 responses)
  • A
    2% (1)
  • B
    83% (44)
  • C
    6% (3)
  • D
    9% (5)

Explanation

The two code fragments that compile are B and E. These are the only ones that use the correct syntax for declaring and initializing a var variable. The var keyword is a reserved type name that allows the compiler to infer the type of the variable based on the initializer expression. However, the var variable must have an initializer, and the initializer must not be null or a lambda expression. Therefore, option A is invalid because it does not have an initializer, option C is invalid because it has a null initializer, and option D is invalid because it has a lambda expression as an initializer. Option B is valid because it has a String initializer, and option E is valid because it has an int initializer. https://docs.oracle.com/en/java/javase/17/language/local-variable-type-inference.html

Topics

#var keyword#local variable type inference#type inference rules#compilation rules

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice