Page 217 - Cs_withBlue_J_C11_Flipbook
P. 217

09                               METHODS AND



                                                                           CONSTRUCTORS















                          Learning Objectives



                     9.1  User-Defined Methods                         9.2  Need for using a Method
                     9.3  Parts of a Method                            9.4  Actual and Formal Parameters
                     9.5  Defining a Function                          9.6  Calling a method
                     9.7  Pure Method and Impure Method                9.8  Method Overloading
                     9.9  Objects and Classes                          9.10 new Operator
                     9.11 this Keyword                                 9.12 Constructor



                 As explained  in  the previous chapter, there are various built-in  methods  in  Java that are already defined  and  a
                 programmer only has to use them in the correct portion of the coding to obtain the required result. Apart from
                 built-in methods, there are also user-defined methods. These methods are declared and defined by the programmer
                 according to the need of the problem.

                     9.1 USER-DEFINED METHODS
                 Sometimes, we may come across certain problems which require executing some tasks repeatedly, but with different
                 input values. This is exactly the situation where we use user-defined methods.
                 Let us take an example.

                  Program 1      Write a program in Java to print the sum and average of two marks 10 and 30 obtained by a
                                 student. Also, the same operation is required to be done for the other student who got 20
                                 and 35 marks.

                   1      class sum_average

                   2      {
                   3          public static void main()
                   4          {

                   5              int m1=10, m2=30, n1=20, n2=35, sum;
                   6              double avg;

                   7              sum = m1+m2;



                                                                                                                       215
                                                                                              Methods and Constructors  215
   212   213   214   215   216   217   218   219   220   221   222