PREV NEXT
- Method is defined as the set of code which performs a specific task and returns any data if provided.
- It is executed, whenever it is invoked.
Method Declaration:
Syntax:
Modifier ReturnType MethodName([Parameter list])
{ //body of the method [return value;]} |
Example:
1 2 3 4 5 6 7 |
public int add(int a, int b) { int c = a+b; return c; } |
Method contains the following components:
1.Modifiers:
They are used to describe the level of access for the method. There are also static and final modifiers which would be explained later. In the above method public is the modifier.
2.Return type:
They are used to specify the type of the data to be returned if required. If no data is to be returned, then void keyword can be used.
3.Method name:
Represents the name of the method, useful for invoking the method. In above method, add is the method’s name.
4.List:
Represents the list of parameters (along with the type) which is passed to the method. Parameters are used for the processing, inside the method. Parameters are optional. Two integer parameters a and b are passed in the above method for adding two numbers.
5.Method Body:
Method body is enclosed within a pair of curly braces. They tell the method what to perform. In the add() method, two integer values are added, the result is of addition is returned.
Invoking a method:
A method can be invoked any number of times, by using the object of the class in which the method is declared followed by the dot operator.
If a invoking method is present in the same class as the method to be invoked, object reference or dot operator is not required. Mostly, internal calculations or something that is needed only within that particular class will be defined and invoked without object reference like this.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Addition { public int add(int a, int b) { return (a+b); } } class MainClass { public static void main(String args[]) { Addition obj = new Addition(); int r = obj.add(4,8); //add method invoked System.out.println(“Result of (4+8):”+r); System.out.println(“Result of (5+6):”+obj.add(5,6)); //add method invoked } } |
Here 4,8 are the arguments which are passed to the method definition. The type of the argument passed must match the type of the parameters defined in the method’s definition. A method can also have reference type like array, objects as parameters.