Monday, 30 January 2012

Methods in Java

Introduction:

•A method is a set of instructions which is used to perform a certain task.

Syntax for declaring a method is as follows:
return-type method-name(parameters)
{
     statement(s);
}


•The return-type of the method can be any of the eight primitive types or a user-defined type.
•If the method does not return any value, then the return-type must be “void”.
•Parameters are used to receive the arguments which are passed during a method call.


Methods returning a value:
•If the called method have to return to a calling method, we must use a “return” statement within the called method.

Syntax is as shown below:
return-type method-name(parameters)
{
    statement(s);
    return value;
}

Parameterized Methods:

•By declaring parameters in the method definition, we are generalizing the methods to accept any kind of values.
•Syntax is as shown below:


return-type method-name(type param1, type param2, …)

{

   statement(s);

   return value;

}

No comments:

Post a Comment