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…
Question
- public class HRapp {
- var employees = new ArrayList<Employee>();
- public void display() {
- var employee = new Employee();
- var offices = new ArrayList<>();
- offices.add("Chicago");
- offices.add("Bangalore");
- for (var office : offices) {
- System.out.print("Employee Location"+ office);
- }
- }
- }
Options
- Aline 13
- Bline 6
- Cline 9
- Dline 8
- Eline 7
How the community answered
(52 responses)- A4% (2)
- B73% (38)
- C8% (4)
- D15% (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
Community Discussion
No community discussion yet for this question.