Page 256 - ComputerScience_Class_11
P. 256

9.7.1 Pure Method
              A pure method is a method that does not change the values passed to it and has no side effects, meaning it does not
              modify any external state or variables. Its output is determined solely by its input parameters, ensuring consistent
              results. A pure method is also typically a returnable method, as it returns a result based on the input values. While
              accessor methods are a type of pure method (if they don’t modify state), not all pure methods are accessor methods.
              Accessor methods specifically retrieve values without changing any state.

              Let us take the following example.
                              Write a program to demonstrate the use of a method that takes an integer as an argument, adds
                Program 6
                              5 to it and then multiplies the result by 5. The program should take an integer as input, pass it to
                              the method and display both the original value and the result returned by the method.
                1       class PureMethod

                2       {
                3           int add(int m1)
                4           {
                5               return (m1 + 5) * 5;

                6           }
                7           public static void main(String[] args)

                8           {
                9               int marks = 50, total;
                10              PureMethod obj = new PureMethod();
                11              total = obj.add(marks);

                12              System.out.println("Actual parameter: " + marks);
                13              System.out.println("Returned value: " + total);

                14          }
                15      }

              The output of the preceding program is as follows:

                     BlueJ: Terminal Window - Java

                 Options

                Actual parameter : 50
                Returned value : 275

              After the execution of the program, the value in the actual parameter remains the same.

              9.7.2 Impure Method
              In Java, an impure method can serve as a mechanism for side effects as it causes a change in the state of an object or
              has side effects, such as modifying instance variables. It is also called a mutator method because it modifies the state
              of an object. While arguments can be passed as reference types (e.g., objects, arrays), the method may also work with
              primitive types passed by value. Impure methods may or may not return a value.






                  254  Touchpad Computer Science (Ver. 3.0)-XI
   251   252   253   254   255   256   257   258   259   260   261