Java Reference
In-Depth Information
The Elements of a Method
A Java method is a collection of declarations and statements, grouped un-
der a single structure, identified by a method name, and designed to per-
form a well-defined task. A Java method contains two clearly identifiable
elements: the declaration and the body . The method is created and defined
in its declaration statement, while the processing operations are contained
in the method body. The following method, named getAverage(), adds all
the elements in an array of int type and returns the average value.
public static int getAverage(int[] intArray)
{
int sum = 0;
// Local variable
// Calculate sum of all array elements
for(intx=0;x<intArray.length; x++)
sum = sum + intArray[x];
// Calculate and return average
return sum / intArray.length;
}
Incidentally...
It is popular among authors of computer topics to follow the method
name with parentheses, for example, main() or getAverage(). This
seems reasonable since parenthesis are characteristic of Java meth-
ods. We follow this convention in this topic.
Declaration
The method declaration, also called the method header , is a single expres-
sion that states the method name and defines the type returned by the
method and the parameters that it receives from the caller, if any. The
method declaration can also contain other information, such as access
specifiers and modifiers. These additional elements determine the
method's visibility and its interaction with other program elements.
The method declaration can also contain exception-handling informa-
tion.ThistopicisdiscussedinthecontextofJavaexceptions,in Chapter
19 . Figure12-1 showstheprincipalelementsinamethoddeclaration.
Programmers note:
The method declaration does not end with a semicolon symbol.
Search WWH ::




Custom Search