суббота, 26 сентября 2026 г.

Call by Value and Call by Reference in Java

Call by Value

When a method is called by passing a value as an argument, it is referred to as call by value. With Java's call-by-value feature, a copy of the variable is passed to the method. As a result, any modifications made within the method only affect that method and do not impact the original variable in the main method.

  • Java always uses call by value, even for objects.
  • When a primitive type (like int, double, float) is passed to a method, a copy of the value is made.
  • Changes inside the method do not affect the original variable.
class Main {

int data = 50;

void change(int data) {
data = data + 100; // changes only the local variable
}

public static void main(String args[]) {

Main op = new Main();

System.out.println("before change " + op.data);

op.change(500);

System.out.println("after change " + op.data);
}
}

    Result:
    before change 50
    after change 50

Call by Reference (Object Reference)

Call by Reference means passing a reference (memory address) of the object by value to a method. Even though Java strictly uses call by value, it duplicates the reference before passing it as a value to the method when we send the reference of an object. The most important difference between call by value and call by reference in Java is that the copied reference also points to the same address, ensuring that all modifications are reflected in the main method.

  • Java does not support true call by reference; it passes the reference by value.
  • When an object is passed, a copy of the reference is made.
  • The reference still points to the same object, so modifications inside the method affect the original object.
class Main {

int data = 50;

void change(Main op) {
op.data = op.data + 100;
}

public static void main(String args[]) {

Main op = new Main();

System.out.println("before change " + op.data);

op.change(op); // passing the object reference

System.out.println("after change " + op.data);
}
}

    before change 50
    after change 150

Комментариев нет:

Отправить комментарий