What will the code shown below print when run?
public class Main{ static class MyClass{ int w = 10; } /* ww w. j a v a 2 s.c o m*/ static MyClass update (MyClass w){ w = new MyClass (); w .w += 9; return w; } public static void main (String [] args){ MyClass w = new MyClass (); w .w = 20; update (w); w .w += 30; System.out.println (w .w); w = update (w); System.out.println (w .w); } }
Select 2 options
A. 9 B. 19 C. 30 D. 20 E. 29 F. 50
Correct Options are : B F
When you pass an object in a method, only its reference is passed by value.
So when update()
does w = new MyClass ();
and then w .w +=9; it does not affect the original wrapper object that was passed to this method.
Therefore, it prints 50.
Calling w = update (w); replaces the original MyClass object with the one created in the update (w); method.
Therefore, in the second print statement, it prints 19.