Pass by Reference in Java

Pass by reference in Java is a method of passing parameters to a method. When a parameter is passed by reference, the method receives a reference to the original object, not a copy of the object. This means that any changes made to the object within the method will be reflected in the original object.

Pass by reference in Java example

Following is an example of pass by reference in Java:

import java.util.*;
public class PassByReference {

    public static void main(String[] args) {
        int[] numbers = new int[]{10, 20, 30};
        System.out.println("The original numbers array is: " + Arrays.toString(numbers));
        changeNumbers(numbers);
        System.out.println("The modified numbers array is: " + Arrays.toString(numbers));
    }

    public static void changeNumbers(int[] numbers) {
        numbers[0] = 100;
        numbers[1] = 200;
        numbers[2] = 300;
    }
}

In this example, the array numbers is passed by reference to the method changeNumbers(). This means that the method does not receive a copy of the array, but rather a reference to the original array. Any changes made to the array within the method will be reflected in the original array.

The output of the program is:

The original numbers array is: [10, 20, 30]
The modified numbers array is: [100, 200, 300]

As we can see, the array numbers is modified by the call to the changeNumbers() method. This is because numbers was passed by reference to the method, and the method was able to modify the original array.

When to use pass by reference

Pass by reference should be used in Java when:

  • We want changes to the parameter to be reflected in the calling method.
  • We need to access the original object reference.

When not to use pass by reference

Pass by reference should not be used in Java when:

  • We do not want changes to the parameter to be reflected in the calling method.
  • We want to avoid the overhead of passing a reference.

FAQs

Does Java support true “pass by reference” like some other languages?

No, Java does not support true “pass by reference” where we can modify the original variable itself. In Java, we can only modify the contents of an object that is referred to by the reference passed to a method.

Are primitive data types passed by reference in Java?

No, primitive data types (e.g., int, float) are passed by value in Java. When we pass a primitive data type as an argument to a method, we are passing a copy of its value, and any changes made inside the method do not affect the original variable.


Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments