Definition of Method
A method is a set of program statements. It forms the fundamental unit of execution in java. Each method exists as part of a class.
During an execution of a program, methods may invoke other methods in the same or a different class. No program code can exist outside a method, and no method can exist outside a class.
Syntax or simplified form of a Method
returnType functionName(parameterlist)
{
body of method
}
Where returnType specifies the return type of a method. This is the type of the value that the method returns to its caller. You must specify a return type for each method. If a method does not return a value, its return type must be declared as void.
functionName is a name of a method.
The optional list of parameters for a method is shown in parameterlist.
Method declaration ca include a clause that indicates the types of executions that can be generated by that method. Syntax is as follows..
returnType functionName(parameterlist) throws exceptionList
{
body of method
}
Where exceptionList is a list that indicates the types of executions that can be generated by this method.
Example of a Method
Example 1 : Method that displays a message.
void fnDisplayMsg()
{
System.out.println("This is my testing method.");
}
Example 2 : Method that displays a message and generates an exception.
void fnDisplayMsg() throws ExceptionX
{
System.out.println("This is my testing method.");
}