Page 203 - computer science (868) class 11
P. 203

15          }
                  16

                  17          void main()
                  18          {

                  19              int number=3456, total;
                  20              System.out.println("Calling method sum with value : " + number);

                  21              total=sum(number); // Variable number is used in Actual parameter
                  22               System.out.println("The sum of all the digits of " + number +" is : " +
                                    total);
                  23          }

                  24      }

                 The output of the preceding program is as follows:
                   Calling method sum with value : 3456

                   Value of num in the beginning : 3456
                   Value of num after calculation : 0
                   The sum of all the digits of 3456 is : 18
                 In the above example,
                 •  sum(number) in the main() contains the actual parameter whose copy is sent to the method int sum(int num).
                 •  After execution of sum(int) method, the value of num is reduced to 0.
                 •  But when num is printed in the main() method after calling the method sum(), the original value of num that is 3456
                   is printed thus having no effect on the caller method.
                 So, we can say that in pass by value, any change in the formal parameters will not reflect on the actual parameters.
                 Also, any type of primitive data can be used in pass by value.

                 8.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 4      Write a program to change all the numbers of array temp[] by 2 in the method sum().


                   1      class pass_reference
                   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++)



                                                                                                                       201
                                                                                              Methods and Constructors  201
   198   199   200   201   202   203   204   205   206   207   208