Sobes.tech
Junior — Middle

Could you explain how argument passing by reference is done in programming?

sobes.tech AI

Answer from AI

In Java, argument passing to methods always occurs by value. This means that a copy of the value is passed to the method.

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 is copied, but not the object itself. Therefore, inside the method, you can change the state of the object the reference points to, but you cannot change the reference itself to point to another object.

Example:

void modify(StringBuilder sb) {
    sb.append(" world"); // modifies the object
    sb = new StringBuilder("new"); // changes the local copy of the reference, does not affect the external object
}

StringBuilder sb = new StringBuilder("Hello");
modify(sb);
System.out.println(sb); // Will output "Hello world"

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.