Can someone solve this quiz question for me? Please Explain!! Java programming!
ID: 3886437 • Letter: C
Question
Can someone solve this quiz question for me? Please Explain!!
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 Int { public long val: public Int (long v) { val = v: } public void prt () { System.out.println(val): } } (i) Int a(6): a.prt(): F/S/R - (ii) Int b = new Int (1): b.prt(): F/S/R- (iii) Int c: c.val = 3: c.prt(): F/S/R- (iv) Int d = new Int (2) e = d: d.val = 8: e.prt(): F/S/R- (v) final Int f = new Int (5): Int g = f: g.val = 7: f.prt(): F/S/R- (vi) final Int h = new Int (4): h.prt(): h = new Int (0): h.prt(): F/S/R-Explanation / Answer
Please find below the detailed description of answers:
class Int {
public long val;
Int(long v)
{
val=v;
}
public void prt()
{
System.out.println(val);
}
}
Questions and Answers
(i) Int a(6);a.prt();
it is a syntax error (S)
in java there is not available way to create object like that
either you need to assign or to variable like below
Int c = new Int(6);
c.prt();
or if only need to call method then use like below
new Int(6).prt();
(ii) Int b = new Int(1);b.prt();
it will Run Fine (F)
as stated in above this is the valid way to create object of java
value of val will be setted to 1
so b.prt() will print 1
(iii)Int c; c.val=3;c.prt();
it is a syntax error (S)
in this c is reference object of Int but it has to be initialize
before using this variable. can initialize like below
c= new Int(4)
(iv)Int d = new Int(2),e=d;
d.val=8;e.prt();
it will Run Fine (F)
in theis d is the object created with param value 2.
e is the reference object of Int class, in simple below code is same equavalent
Int d = new Int(2);
Int e = d;
as you can see it is more clear to understand
e have reference to d object
d.val = 8 then e.prt() will print 8 as it have the same refernce of this object
(v)final f = new Int(5);Int g=f;
g.val=7;f.prt();
it will Run Fine (F)
in this f is the final object means it cant be change or altered
g is reference object that have reference of f.
using g chaning the value of val to 7.
(vi) final Int h = new Int(4);h.prt();
h=new Int(0); h.prt();
it is a syntax error (S)
because it trying to modyfing the final variable which is not permitable
this line of code final Int h = new Int(4);h.prt(); will work fine and print 4
but this h=new Int(0); will cause error.
please do let me know if u have any concern...