Computer Applications
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.
Related Questions
Debug the errors and rewrite the following method prototypes:
(a) int sum(x,y);
(b) float product(a,int y);
(c) float operate(int x, float=3.4);
(d) float sum(int x,y);
Write down the main method which calls the following method:
int square(int a) { return(a*a); }
In what situation does a method return a value?
Differentiate between pure and impure methods.