Page 254 - ComputerScience_Class_11
P. 254
9.6.2 Pass by Reference
The word reference in computer means the address of some variables. In this type of programming, the actual
parameter and the formal parameter share the same location in the memory. This means any change in the formal
parameter while the method is executing, will change the actual parameter also.
Let us take the following example.
Program 5 Write a program to change all the numbers of array temp[] by 2 in the method sum().
1 class PassReference
2 {
3 void sum(int ar[])
4 {
5 int i, len = ar.length;
6 System.out.println("-------------------------------");
7 System.out.println("\nResult before increase by 2:");
8 for(i = 0; i < len; i++)
9 {
10 System.out.print(ar[i] + " ");
11 }
12 for(i = 0; i < len; i++)
13 {
14 ar[i] += 2;
15 }
16
17 System.out.println("\n-------------------------------");
18 System.out.println("\nResult after increase by 2:");
19 for(i = 0; i < len; i++)
20 {
21 System.out.print(ar[i] + " ");
22 }
23 System.out.println();
24 }
25 public static void main(String[] args)
26 {
27 int arr[] = {45, 34, 26, 67, 78, 98};
28 int i;
29 System.out.println("\nValue in original array arr[] in main():");
30 for(i = 0; i < arr.length; i++)
252 Touchpad Computer Science (Ver. 3.0)-XI

