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
wis passed to thechangeWrapperfunction. In the changeWrapper function, a new Wrapper object is created and assigned to the passed in reference. So now,wis pointing to a new Wrapper object and so the value ofwis 10. Nine is added to this value and an object is returned withw.wequal to 19. - At line 4, 30 is added so now
w.wis 49. - At line 5, 49 should be printed out.
- At line 6, the Wrapper object with
w.wequal to 49 is passed to thechangeWrappermethod. Inside that method, a new Wrapper object is created and an object is returned with the value ofw.wset to 19. This reference to this object is then assigned tow. So nowwpoints to an object withw.wset to 19. So, 19 is printed out as expected.
Why is 50 printed out instead of 49?