Java – How to change the reference using a method?

This question already has an answer here:

  • Is Java “pass-by-reference” or “pass-by-value”?

    71 answers

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?

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