nerdexam
Oracle

1Z0-819 · Question #138

Given: class Employee { String office; } and the code fragment: 5. public class HRapp { 6. var employees = new ArrayList<Employee>(); 7. public void display() { 8. var employee = new Employee(); 9…

The correct answer is B. line 6 E. line 7. Note on the stated answer: There appears to be an error in this question's answer key. The two actual compilation errors are on line 6 (B) and line 9 (C), not B and E. Here is the accurate explanation: Line 6 (B) fails because var (local variable type inference, Java 10+) is…

Working with Java Data Types

Question

Given: class Employee { String office; } and the code fragment:
  1. public class HRapp {
  2. var employees = new ArrayList<Employee>();
  3. public void display() {
  4. var employee = new Employee();
  5. var offices = new ArrayList<>();
  6. offices.add("Chicago");
  7. offices.add("Bangalore");
  8. for (var office : offices) {
  9. System.out.print("Employee Location"+ office);
  10. }
  11. }
  12. }
Which two lines cause compilation errors? (Choose two.)

Options

  • Aline 13
  • Bline 6
  • Cline 9
  • Dline 8
  • Eline 7

How the community answered

(52 responses)
  • A
    4% (2)
  • B
    73% (38)
  • C
    8% (4)
  • D
    15% (8)

Explanation

Note on the stated answer: There appears to be an error in this question's answer key. The two actual compilation errors are on line 6 (B) and line 9 (C), not B and E. Here is the accurate explanation:

Line 6 (B) fails because var (local variable type inference, Java 10+) is restricted to local variables only - it cannot be used for instance fields (class-level variables). Declaring var employees = ... outside any method body is illegal.

Line 9 (C) fails because combining var with the diamond operator <> creates circular inference: the diamond needs a target type to infer type arguments, while var needs the initializer to determine the variable's type. Neither can resolve without the other, so var offices = new ArrayList<>() is explicitly forbidden by the Java spec. Fixing it requires var offices = new ArrayList<String>() or ArrayList<String> offices = new ArrayList<>().

Why the distractors are wrong: Line 7 (public void display()) is a valid instance method declaration. Line 8 (var employee = new Employee()) is valid - var with an explicit concrete type on the right side works fine inside a method. Line 13 is valid Java; string concatenation with + on an Object-typed variable calls .toString() implicitly.

Memory tip: Think of var as needing one explicit type to latch onto - if it's outside a method (field) or paired with another "figure-it-out" operator like <>, neither side has an anchor and the compiler refuses.

Topics

#var keyword#type inference#field declarations#local variables

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice