** As we know that, classes usually consists of two things : instance variables and methods . the topic of methods is large one because Java gives them so much power and flexibility .
- It is a sub-program which is having a statement or a group of statements to perform a particular task
- With the help of methods we can avoid the redundancy of the code , it reduces the length of the program and efficiency of the program will be increased .
- Basically , methods are classified into two categories
1. pre-defined methods
2. User-defined methods
1. The method which are existed along with the JDK is known as pre-defined methods .
2. The methods which are defined by the programmer for the programming requirement , those methods are called as user-defined methods .
syntax : [modifier] <returntype> <methodName>(parameter list)
- The keyword within the square brackets is optional . That is , modifier is optional . If the method does not return a value , it’s <returntype> is void.
- The parameter-list is a sequence of type and identifier pairs separated by commas. parameter-list are also known as formal arguments . Parameters are essential variables that receive the value of the arguments passed to the method when it is called.
A SIMPLE PROGRAM :
CLICK ON THE PROGRAM:
TRACING OF THE ABOVE PROGRAM
- First , the controller searches for the signature “public static void main(String args)” > That is , you are specifying the Java run-time system to start from there .
- Then the , controller enters into the main method , executes the line 18 and ‘b’ object is created . Every object has it’s own space in the memory , we can create N number of objects to a class . That is, N number of objects will have their own space in the memory in the heap organisation .
- Now , in the lines 21,22,23 : we are assigning the values to the instance variables with the help of object ‘b’ . These values to the width, height and depth will be stored in ‘b’ object in the heap organisation(objects generally will be stored in heap organisation) .Here you have to remember that, every object has its own copy of instance variables separately . Here you have created two objects ‘b’ and ‘b1’ , now , each object ‘b’ and ‘b1’ will have the copy of instance variables in their respected memory separately .
- When you are calling the volume() method with respect to ‘b’ object , what ever the values we have stored in ‘b’ object , those values will be taken by the volume() method respectively .