KnowledgeBoat Logo

Computer Applications

What happens when a method is passed by reference? Explain.

User Defined Methods

30 Likes

Answer

Pass by reference means that the arguments of the method are a reference to the original objects and not a copy. So any changes that the called method makes to the objects are visible to the calling method. Consider the example given below:


class PassByReferenceExample {
    public void demoRef(int a[]) {
        for (int i = 0; i < 5; i++) {
            a[i] = i;
        }
    }

    public static void main(String args[]) {
        PassByReferenceExample obj = new PassByReferenceExample();
        int arr[] = { 10, 20, 30, 40, 50 };
        System.out.println("Before call to demoRef value of arr");
        for (int i = 0; i < 5; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
        obj.demoRef(arr);
        System.out.println("After call to demoRef value of arr");
        for (int i = 0; i < 5; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

The output of this program is:

Before call to demoRef value of arr
10 20 30 40 50
After call to demoRef value of arr
0 1 2 3 4

Here demoRef changes the values of array a and these changes are reflected in the array in the main method as well.

Answered By

13 Likes


Related Questions