Properties of methods. A complete detailed description of the properties of methods
is beyond our scope, but the following points are worth noting:
■ Arguments are passed by value. You can use argument variables anywhere in the
code in the body of the method in the same way you use local variables. The
only difference between an argument variable and a local variable is that the
argument variable is initialized with the argument value provided by the calling
code. The method works with the value of its arguments, not the arguments
themselves. One consequence of this approach is that changing the value of an
argument variable within a static method has no effect on the calling code. Generally,
we do not change argument variables in the code in this book. The passby-
value convention implies that array arguments are aliased (see page 19)—the
method uses the argument variable to refer to the caller’s array and can change
the contents of the array (though it cannot change the array itself). For example,
Arrays.sort() certainly changes the contents of the array passed as argument:
it puts the entries in order.
■
Method names can be overloaded. For example, the Java Math library uses
this approach to provide implementations of Math.abs(), Math.min(), and
Math.max() for all primitive numeric types. Another common use of overloading
is to define two different versions of a function, one that takes an argument
and another that uses a default value of that argument.
■ A method has a single return value but may have multiple return statements. A
Java method can provide only one return value, of the type declared in the
method signature. Control goes back to the calling program as soon as the first
return statement in a static method is reached. You can put return statements
wherever you need them. Even though there may be multiple return statements,
any static method returns a single value each time it is invoked: the value following
the first return statement encountered.
■ A method can have side effects. A method may use the keyword void as its return
type, to indicate that it has no return value. An explicit return is not necessary
in a void static method: control returns to the caller after the last statement.
A void static method is said to produce side effects (consume input, produce
output, change entries in an array, or otherwise change the state of the system).
For example, the main() static method in our programs has a void return type
because its purpose is to produce output. Technically, void methods do not
implement mathematical functions (and neither does Math.random(), which
takes no arguments but does produce a return value).
The instance methods that are the subject of Section 2.1 share these properties, though
profound differences surround the issue of side effects.