Sobes.tech
Junior

What does passing parameters by value mean?

sobes.tech AI

Answer from AI

Passing parameters by value means that a copy of the variable's value is passed to the method. Any changes made to the parameter inside the method do not affect the original variable outside the method.

For primitive types (such as int, float, boolean, etc.) - a copy of the actual value is passed.

For reference types (objects) - a copy of the reference to the object is passed. This means that inside the method, you can modify the object that the parameter references (for example, change the object's fields), and these changes will be visible outside the method, since both references point to the same object in memory. However, if the reference itself is assigned a new object inside the method (creating a new object and assigning it to the parameter), the original reference outside the method remains unchanged.

Example for a primitive type:

public class PassByValueExample {

    public static void changeValue(int number) {
        number = number + 10; // Modifying the copy of the value
        // System.out.println("Inside method: " + number); // For demonstration
    }

    public static void main(String[] args) {
        int x = 5;
        changeValue(x);
        // System.out.println("Outside method: " + x); // x will remain 5
    }
}

Example for a reference type:

class MyObject {
    int value;

    MyObject(int value) {
        this.value = value;
    }
}

public class PassByValueReferenceExample {

    public static void modifyObject(MyObject obj) {
        obj.value = obj.value + 10; // Modifying the object's field via the reference
    }

    public static void reassignObject(MyObject obj) {
        obj = new MyObject(100); // Assigning a new object to the parameter
        // System.out.println("Inside reassignObject: " + obj.value); // For demonstration
    }

    public static void main(String[] args) {
        MyObject myObj = new MyObject(5);
        modifyObject(myObj);
        // System.out.println("After modifyObject: " + myObj.value); // value will be 15

        MyObject anotherObj = new MyObject(20);
        reassignObject(anotherObj);
        // System.out.println("After reassignObject: " + anotherObj.value); // value remains 20
    }
}
What does passing parameters by value mean? — Java - sobes.tech