Java Reference
In-Depth Information
Let's look at a method defined to find the larger between two integers. This method, named
max
, has two
int
parameters,
num1
and
num2
, the larger of which is returned by the method.
Figure 5.1 illustrates the components of this method.
Define a method
Invoke a method
return value
type
method
name
formal
parameters
modifier
method
header
public static int
max(
int
num1,
int
num2) {
int
z = max(x, y);
int
result;
method
body
actual parameters
(arguments)
parameter list
method
signature
if
(num1 > num2)
result = num1;
else
result = num2;
return
result;
return value
}
F
IGURE
5.1
A method definition consists of a method header and a method body.
The
method header
specifies the
modifiers
,
return value type
,
method name
, and
parameters
of the method. The
static
modifier is used for all the methods in this chapter.
The reason for using it will be discussed in Chapter 8, Objects and Classes.
A method may return a value. The
returnValueType
is the data type of the value the
method returns. Some methods perform desired operations without returning a value. In this
case, the
returnValueType
is the keyword
void
. For example, the
returnValueType
is
void
in the
main
method, as well as in
System.exit
,
System.out.println
, and
JOptionPane.showMessageDialog
. If a method returns a value, it is called a
value-
returning method
, otherwise it is called a
void method.
The variables defined in the method header are known as
formal parameters
or simply
parameters.
A parameter is like a placeholder: When a method is invoked, you pass a value to
the parameter. This value is referred to as an
actual parameter or argument.
The
parameter
list
refers to the method's type, order, and number of the parameters. The method name and
the parameter list together constitute the
method signature.
Parameters are optional; that is, a
method doesn't have to contain any parameters. For example, the
Math.random()
method
has no parameters.
The method body contains a collection of statements that implement the method. The
method body of the
max
method uses an
if
statement to determine which number is larger
and return the value of that number. In order for a value-returning method to return a result, a
return statement using the keyword
return
is
required.
The method terminates when a return
statement is executed.
method header
modifier
value-returning method
void method
formal parameter
parameter
actual parameter
argument
parameter list
method signature
Note
Some programming languages refer to methods as
procedures
and
functions.
In those
languages, a value-returning method is called a
function
and a void method is called a
procedure.
Caution
In the method header, you need to declare each parameter separately. For instance,
max(int num1, int num2)
is correct, but
max(int num1, num2)
is wrong.