What will the following class print when compiled and run?
public class Main { int value = 1; Main v;/* w w w. j a va 2 s.co m*/ public Main(int val) { this.value = val; } public static void main(String[] args) { final Main a = new Main(5); Main b = new Main(10); a.v = b; b.v = setIt(a, b); System.out.println(a.v.value + " " + b.v.value); } public static Main setIt(final Main x, final Main y) { x.v = y.v; return x; } }
Select 1 option
setIt()
cannot change x.v. Correct Option is : E
For Option A.
'a' is final is true, a will keep pointing to the same object for the entire life of the program.
The object's internal fields, however, can change.
For Option B.
Since x and y are final, the method cannot change what x and y to point to some other object but it can change the objects' internal fields.
For Option E.
When method setIt()
executes, x.v = y.v, x.v becomes null because y.v is null so a.v.value throws NullPointerException.