Can someone please solve this and provide a clear explanation? (java programming
ID: 3886443 • Letter: C
Question
Can someone please solve this and provide a clear explanation? (java programming)
Given the following Java class, indicate for each code fragment below whether it compiles and runs fine (F) or if there is a syntax error (S) or a runtime error (R). State in each case what the output or the error is. class Age { public int years = 0: //default public Age(int y) { years = y, ) public void prt() { System.out println(years): } (i) Age a=new Age(10), a prt(): F/S/R (ii)Age b() b part() F/S/R (iii) Age c, c years = 14 c prt(), F/S/R (iv) Age d=new Age(4), Age e = d d years = 8 e part() F/S/R (v) final Age f=new Age(9) Age g=f, g years=3, f prt() F/S/R (vi) final Age h=new Age(6) h prt(), h=new Age(20). h prt(), F/S/RExplanation / Answer
1. It runs fine and gives output 10.
The reason is that it creates properly the object and then calls the funtion prt() which changes the value of years to 10 and displays it on the screen.
2.Sytax Error
The error is an syntax error which states that it must initialize the variable above as the values are not given and must be provided to the constructor.
3.Syntax Error
The initialization of the value of years is very important which is been missing in the program and when the object is made no value is passed to the constructor because of which the error is raising.
Age(int years) but when you are passing the value to the constructor it is empty Age(); Hence, facing syntax error.
4. Runs Fine
The object creation is fine and the syntax is also good. All the things that depends on the callng is cool. And the output will be 8. Because the value for years is initialized to 4 first and then one more object is created which focuses on new value of years and sets it to 8 and then the function is called which prints the value 8.
5. Runs Fine
The code is good without any syntax errors. Final keyword is only used to stop method overriding . In the above code the variable f is set as final but the changes is been done with the help of g which is not at all final and hence, the code runs and displays 3 as output.
6. Runtime Error
It states an runtime error that values for final cannot be changed and the code changes the value for the final keyword. Hence, it states the error that value for final variable cannot be changed.
Rate an upvote.....Thankyou
Hope this helps.....