Call by Value and Call by Reference

Author: Ravi Poswal

Call by Value: The formal parameters have the same value as the actual parameters. It means the value of the actual parameter is copied into the formal parameter during a method call.

  • The method works on the copied value, not the original variable.

  • Changes made inside the method do not affect the actual parameter.

  • Separate memory is allocated for actual and formal parameters.

  • The actual parameter is the argument passed in the method call.

  • The formal parameter is the variable defined in the method that receives the copied value.

Code Example

class Call {
   public void value(int x) {
        x = 35;
    }

    public static void main(String[] args) {
        int a = 10;
        Call r = new Call();
        r.value(a);
        System.out.println(a);
    }
}

Call by Reference

java does not support truly call by reference.but usiing objects may look like they are passed by reference, but actually they are not. When we pass an object to a method, a copy of its reference (memory address) is sent. Both the original reference and the copied reference point to the same object in memory. Because of this, changes made to the object inside the method are visible outside the method.

Code Example

class Ref {
    int marks = 10;
}
class Call {
    void value(Ref s) {
        s.marks = 25;
    }

    public static void main(String[] args) {
        Ref s1 = new Ref();
        Call t = new Call();
        t.change(s1);
        System.out.println(s1.marks);
    }
}

FAQs

1. It means the value of the actual parameter is copied into the formal parameter during a method call.

2. The method works on the copied value, not the original variable.

3. Changes made inside the method do not affect the actual parameter.

No, Java does not support true call by reference. It only uses call by value for all types of data.

Objects appear to behave like call by reference because a copy of the reference (memory address) is passed, and both references point to the same object.

No, changing the reference inside the method does not affect the original reference outside the method.

The actual parameter is the value passed during a method call, while the formal parameter is the variable that receives the value inside the method.

Yes, in call by value, separate memory is allocated for the copied value of the parameter.

class Test {
void add(int x, int y) { // x and y are parameters
System.out.println(x + y);
}

public static void main(String[] args) {
Test t = new Test();
t.add(5, 10); // 5 and 10 are arguments
}
}