The following code is printing out values which are unexpected to me; the code is printing out 50 and then 19. Below I have set out my reasoning, please can someone correct the error in my reasoning process:
class Wrapper{
int w = 10;
}
public class Main {
static Wrapper changeWrapper(Wrapper w){
w = new Wrapper();
w.w += 9;
return w;
}
public static void main(String[] args) {
Wrapper w = new Wrapper(); // line 1
w.w = 20; // line 2
changeWrapper(w); // line 3
w.w += 30; // line 4
System.out.println(w.w); // line 5
w = changeWrapper(w); // line 6
System.out.println(w.w); // line 7
}
}
Reasoning Process:
- At line 1, a new Wrapper object is created and the value of w.w is 10.
- At line 2, the value of w.w is set to 20.
- At line 3, a reference to
w
is passed to thechangeWrapper
function. In the changeWrapper function, a new Wrapper object is created and assigned to the passed in reference. So now,w
is pointing to a new Wrapper object and so the value ofw
is 10. Nine is added to this value and an object is returned withw.w
equal to 19. - At line 4, 30 is added so now
w.w
is 49. - At line 5, 49 should be printed out.
- At line 6, the Wrapper object with
w.w
equal to 49 is passed to thechangeWrapper
method. Inside that method, a new Wrapper object is created and an object is returned with the value ofw.w
set to 19. This reference to this object is then assigned tow
. So noww
points to an object withw.w
set to 19. So, 19 is printed out as expected.
Why is 50 printed out instead of 49?