Page 253 - ComputerScience_Class_11
P. 253

3          int sum(int num)

                   4          {
                   5              int rem = 0, s = 0;
                   6              System.out.println("Value of num in the beginning: " + num);
                   7              while(num > 0)

                   8              {
                   9                  rem = num % 10;
                  10                  s = s + rem;
                  11                  num = num / 10;
                  12              }
                  13              System.out.println("Value of num after calculation: 0");

                  14              return s;
                  15          }
                  16          public static void main(String[] args)
                  17          {

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

                                   System.out.println("The sum of all the digits of " + number + " is: "
                  22                + total);
                  23          }
                  24      }


                 The output of the preceding program is as follows:
                       BlueJ: Terminal Window - Java

                   Options

                  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.





                                                                                           Methods and Constructors  251
   248   249   250   251   252   253   254   255   256   257   258