Page 255 - ComputerScience_Class_11
P. 255

31              {

                  32                  System.out.print(arr[i] + " ");
                  33              }

                  34              PassReference obj = new PassReference();
                  35              obj.sum(arr);
                  36              System.out.println("-------------------------------");

                  37               System.out.println("\nValues of original array arr[] in main() after
                                    calling sum():");
                  38
                  39              for(i = 0; i < arr.length; i++)
                  40              {

                  41                  System.out.print(arr[i] + " ");
                  42              }

                  43          }
                  44      }
                 The output of the preceding program is as follows:


                       BlueJ: Terminal Window - Java
                   Options

                  Value in original array arr[] in main():
                  45 34 26 67 78 98 -------------------------------
                  Result before increase by 2:
                  45 34 26 67 78 98 -------------------------------

                  Result after increase by 2:
                  47 36 28 69 80 100 -------------------------------
                  Values of original array arr[] in main() after calling sum():
                  47 36 28 69 80 100


                 The above example followed the sequence given below:
                 •  From main(), array ar when printed we get, 45 34 26 67 78 98
                 •  Then sum(arr) method is invoked
                 •  In the sum(int ar) method before increasing by 2, the values printed are 45 34 26 67 78 98
                 •  After increasing by 2, the values printed are 47 36 28 69 80 100
                 •  At last, when the array is printed after the call of sum(), we get 47 36 28 69 80 100 in the array ar even though the
                   values are not returned.
                 So, in pass by reference any change to the formal parameters will also reflect on the actual parameters. Also, only
                 non-primitive data can be used in pass by reference.


                     9.7 PURE METHOD AND IMPURE METHOD
                 Pure and impure methods are two programming terms we often see in functional programming. Let us read about
                 them in detail.




                                                                                           Methods and Constructors  253
   250   251   252   253   254   255   256   257   258   259   260