March 02, 2015

What is the result when we try to Compile and Run ?

Given:

11. public class ItemTest {
12. private final int id;
13. public ItemTest(int id) { this.id = id; }
14. public void updateId(int newId) { id = newId; }
15. 
16. public static void main(String[] args) {
17. ItemTest fa = new ItemTest(42);
18. fa.updateId(69);
19. System.out.println(fa.id);
20. }
21. }




A. Compilation fails.
B. An exception is thrown at runtime.
C. The attribute id in the ItemTest object remains unchanged.
D. The attribute id in the ItemTest object is modified to the new value.
E. A new ItemTest object is created with the preferred value in the id attribute.









Answer: A


Explanation :

When you Compile and run the above program you get 

ItemTest.java:14:error: Cannot Assign value to final variable id 
 public void updateId(int newId) { id = newId; }
                                   ^
1 error .

Compilation fails because once we assign a value to final variable we can't change its value again .This is not because id is marked private or we haven't used this.id in updateId method .

Remember when you mark any variable as final ,Only once we can assign value to it and we can't change its value again.Burn that in.





Related Topics

1 comment: