Sobes.tech
Junior — Middle

How is variable passing by reference implemented when calling methods?

sobes.tech AI

Answer from AI

In Java, parameter passing to methods always occurs by value, meaning the variable's value is copied. However, if an object is passed, the reference to the object is copied, not the object itself. This is often called "pass by reference," but in reality, a copy of the reference is passed.

This means that within the method, you can modify the state of the object the parameter refers to, but you cannot change the reference itself to point to a different object.

Example:

class MyObject {
    int value;
}

public class Example {
    public static void modifyObject(MyObject obj) {
        obj.value = 10; // change the object's state
        obj = new MyObject(); // change the local copy of the reference
        obj.value = 20; // this change will not affect the object outside the method
    }

    public static void main(String[] args) {
        MyObject myObj = new MyObject();
        myObj.value = 5;
        modifyObject(myObj);
        System.out.println(myObj.value); // will print 10
    }
}

Here, it is clear that changing the object's state inside the method persists, but reassigning the reference does not.

How is variable passing by reference implemented when… - sobes.tech