Java Reference
In-Depth Information
supply for the parameters when you call a method are described as arguments . The parameter names are
used in the body of the method to refer to the corresponding argument values that you supply when you call
the method. Your methods do not have to have parameters specified. A method that does not require any
information to be passed to it when it is executed has an empty pair of parentheses after the name.
Returning from a Method
To return a value from a method when its execution is complete you use a return statement. For example
return return_value; // Return a value from a method
After executing the return statement in a method, the program continues from the point where the meth-
od was called. The value return_value that is returned by the method can be any expression that produces
a value of the type specified for the return value in the declaration of the method. Methods that return a
value — that is, methods declared with a return type other than void — must always finish by executing a
return statement that returns a value of the appropriate type. Note, though, that you can put several return
statements within a method if the logic requires this. If a method does not return a value, you can just use
the keyword return by itself to end execution of the method:
return; // Return from a method
For methods that do not return a value, falling through the closing brace enclosing the body of the method
is equivalent to executing a return statement.
The Parameter List
The parameter list appears between the parentheses following the method name. This specifies the type of
each value that can be passed as an argument to the method, and the variable name that is used in the body of
the method to refer to each argument value passed to the method when it is called. The difference between a
parameter and an argument is sometimes confusing because people often, incorrectly, use them interchange-
ably. I try to differentiate them consistently, as follows:
• A parameter has a name and a type and appears in the parameter list in the definition of a method.
A parameter defines the type of value that can be passed to the method when it is called.
• An argument is a value that is passed to a method when it is executed, and the value of the argu-
ment is referenced by the parameter name during execution of the method. Of course, the type of
the argument value must be consistent with the type specified for the corresponding parameter in
the definition of the method.
This is illustrated in Figure 5-3 .
FIGURE 5-3
 
 
Search WWH ::




Custom Search