I'm preparing to take OCJP exam and I have a tricky question. I don't know why the correct answer is the next one : "B. 300-300-100-100-100" The question sounds like this:
1. class Foo {
2. private int x;
3. public Foo(int x) {
4. this.x = x;
5. }
6. public void setX(int x) {
7. this.x = x;
8. }
9. public int getX() {
10. return x;
11. }
12. }
13. public class Gamma {
14. static Foo fooBar(Foo foo) {
15. foo = new Foo(100);
16. return foo;
17. }
18. public static void main(String[] args) {
19. Foo foo = new Foo(300);
20. System.out.println(foo.getX() + "-");
21. Foo fooBoo = fooBar(foo);
22. System.out.println(foo.getX() + "-");
23. System.out.println(fooBoo.getX() + "-");
24. foo = fooBar(fooBoo);
25. System.out.println(foo.getX() + "-");
26. System.out.println(fooBoo.getX() + "-");
27. }
28. }
Frankly speaking I was expected that correct answer should be "A. 300-100-100-100-100" because at line 15 foo reference is changed to a new Foo object which has as instance variable x=100 and I don't know why at line 22 foo reference is to the "old object" with instance variable x=300
Can someone explain me why? Thanks!