Reputation: 706
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!
Upvotes: 1
Views: 391
Reputation: 320
This is how objects work in Java
Foo fooBoo = fooBar(foo); // here foo ---> 300
//function fooBar call
foo = new Foo(100);
This line will create new foo object pointing to 100 so it will look like this
foo (passed to method) ----> 300
foo (created inside method) ---> 100
That is why the value is not changing in that step
Upvotes: 0
Reputation: 4841
Reference to the foo variable is changed on the line 24. It is not changed at line 15. because original foo was hidden by local foo variable of static method fooBar.
Upvotes: 3
Reputation: 36304
Explaining inline :
public static void main(String[] args) {
19. Foo foo = new Foo(300);
20. System.out.println(foo.getX() + "-"); // 300
21. Foo fooBoo = fooBar(foo); // foo is "unchanged" here
22. System.out.println(foo.getX() + "-"); // printing foo --> 300
23. System.out.println(fooBoo.getX() + "-"); // printing fooBoo --> 100
24. foo = fooBar(fooBoo); // changing foo and setting it to 100
25. System.out.println(foo.getX() + "-"); // So foo will be --> 100
26. System.out.println(fooBoo.getX() + "-");// fooBoo is already -->100
27. }
Upvotes: 5