Sobes.tech
Junior — Middle

What is the difference between passing arguments by reference and by value when calling a function?

sobes.tech AI

Answer from AI

Passing arguments by value means that a copy of the argument's value is passed to the function. Changes inside the function do not affect the original variable outside the function.

Passing by reference means that a reference to the original object is passed to the function, and changes inside the function are reflected on this object outside the function.

In Java, all primitive types are passed by value, and objects are passed by value of the reference (i.e., a copy of the reference to the object is passed, but not the object itself). This means that inside the method, you can change the state of the object, but you cannot reassign the reference itself to affect the variable outside the method.

Example:

public class Example {
    public static void modifyPrimitive(int x) {
        x = 10; // modifying the local copy
    }

    public static void modifyObject(StringBuilder sb) {
        sb.append(" world"); // modifying the object
    }

    public static void main(String[] args) {
        int a = 5;
        modifyPrimitive(a);
        System.out.println(a); // Will print 5, as primitive is passed by value

        StringBuilder sb = new StringBuilder("Hello");
        modifyObject(sb);
        System.out.println(sb.toString()); // Will print "Hello world", as the object is modified through the reference
    }
}
What is the difference between passing arguments by… - sobes.tech