1

I am trying to change the reference of an object and I wrote the following code.

public class Test {
    public static void main(String[] args) {
        Foo foo1 = new Foo();
        Foo foo2 = new Foo();
        System.out.println("the reference of foo1 is " + foo1);
        System.out.println("the reference of foo2 is " + foo2);
        System.out.println();
        change(foo1, foo2);
        System.out.println("the reference of foo1 is " + foo1);
        System.out.println("the reference of foo2 is " + foo2);
    }

    public static void change(Foo foo1, Foo foo2) {
        System.out.println("the reference of foo1 is " + foo1);
        System.out.println("the reference of foo2 is " + foo2);
        System.out.println();
        foo1 = foo2;
        System.out.println("the reference of foo1 is " + foo1);
        System.out.println("the reference of foo2 is " + foo2);
        System.out.println();
    }
}

class Foo {
    public Foo() {
        // do nothing
    }
}

I got the following output.

the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c

the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c

the reference of foo1 is Foo@6d06d69c
the reference of foo2 is Foo@6d06d69c

the reference of foo1 is Foo@15db9742
the reference of foo2 is Foo@6d06d69c

The change method changed the reference of foo1 from Foo@15db9742 to Foo@6d06d69c in the change method, but the reference of foo1 did not change in the main method. Why?

sotanishy
  • 15
  • 1
  • 6
  • I don't know what you mean by "change the reference of an object", but I strongly suspect that your question will be answered [on this page](https://stackoverflow.com/q/40480) - so much so that I'm tempted to close this as a duplicate. – Dawood ibn Kareem Jul 31 '17 at 21:58
  • @Reimeus The marked duplicate is incorrect. The question is about passing references. in Java, references are passed as COPIES into methods. Any re-assignments remain local to that scope only. – Kon Jul 31 '17 at 21:58

1 Answers1

1

In Java, all arguments to methods are passed by value. Note that variables of non-primitive type, which are references to objects, are also passed by value: in that case, a reference is passed by value.

So in your case the modification you do in your function does not change the object using in your main

jeanr
  • 1,031
  • 8
  • 15