Sobes.tech
Junior — Middle

Explain what happens when passing a variable by reference in a function or method.

sobes.tech AI

Answer from AI

In Java, parameter passing to methods always occurs by value. This means that when passing a variable to a method, the value of the variable is copied.

For primitive types (int, boolean, etc.), the actual value is copied.

For objects, the value of the reference to the object is copied, meaning a pointer to the object is copied, not the object itself. Therefore, inside the method, you can change the state of the object that the parameter references, but you cannot change the reference itself to point to another object outside the method.

Example:

public class Example {
    public static void modifyObject(MyObject obj) {
        obj.value = 10; // changes the object's field
        obj = new MyObject(); // local change to the reference, does not affect the external object
        obj.value = 20;
    }

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

class MyObject {
    int value;
}

Thus, in Java, there is no passing by reference in the classical sense; there is passing by value, where a copy of the reference is passed for objects.