Java Reference
In-Depth Information
Defining Methods
In Java, a method definition has four basic parts:
The name of the method
n
A list of parameters
n
The type of object or primitive type returned by the method
n
The body of the method
n
The first two parts of the method definition form the method's signature .
NOTE
To keep things simpler today, two optional parts of the method
definition have been left out: a modifier, such as public or
private , and the throws keyword, which indicates the exceptions a
method can throw. You learn about these parts of method defini-
tion on Day 6, “Packages, Interfaces, and Other Class Features,”
and Day 7, “Exceptions, Assertions, and Threads.”
In other languages, the name of the method (which might be called a function, subrou-
tine, or procedure) is enough to distinguish it from other methods in the program.
In Java, you can have several methods in the same class with the same name but different
signatures. This practice is called method overloading , and you learn more about it
tomorrow.
Here's what a basic method definition looks like:
returnType methodName( type1 arg1 , type2 arg2 , type3 arg3 ...) {
// body of the method
}
The returnType is the primitive type or class of the value returned by the method. It can
be one of the primitive types, a class name, or void if the method does not return a value
at all.
The method's parameter list is a set of variable declarations separated by commas and set
inside parentheses. These parameters become local variables in the body of the method,
receiving their values when the method is called.
Note that if this method returns an array object, the array brackets can go after either the
returnType or the closing parenthesis of the parameter list. Because the former way is
Search WWH ::




Custom Search