nerdexam
Oracle

1Z0-851 · Question #27

Given: public class ItemTest { private final int id; public ItemTest(int id) { this.id = id; } public void updateId(int newId) { id = newId; } public static void main(String[] args) { ItemTest fa =…

The correct answer is A. Compilation fails. The final field ItemTest.id cannot be assigned

Analyzing and Troubleshooting System Problems

Question

Given: public class ItemTest { private final int id; public ItemTest(int id) { this.id = id; } public void updateId(int newId) { id = newId; } public static void main(String[] args) { ItemTest fa = new ItemTest(42); fa.updateId(69); System.out.println(fa.id); } } What is the result?

Options

  • ACompilation fails.
  • BAn exception is thrown at runtime.
  • CThe attribute id in the ItemTest object remains unchanged.
  • DThe attribute id in the ItemTest object is modified to the new value.
  • EA new ItemTest object is created with the preferred value in the id attribute.

How the community answered

(40 responses)
  • A
    73% (29)
  • C
    8% (3)
  • D
    18% (7)
  • E
    3% (1)

Explanation

The final field ItemTest.id cannot be assigned

Topics

#Java final field#constructor#compilation error#immutability

Community Discussion

No community discussion yet for this question.

Full 1Z0-851 Practice