Method Parameters
Let us review the computer science terms that describe how parameters can be passed to a method (or a function) in a programming language. The term call by value means that the method gets just the value that the caller provides. In contrast, call by reference means that the method gets the location of the variable that the caller provides. Thus, a method can modify the value stored in a variable that is passed by reference but not in one that is passed by value. These "call by . . . " terms are standard computer science terminology that describe the behavior of method parameters in various programming languages, not just Java. (In fact, there is also a call by name that is mainly of historical interest, being employed in the Algol programming language, one of the oldest high-level languages.)
The Java programming language always uses call by value. That means, the method gets a copy of all parameter values. In particular, the method cannot modify the contents of any parameter variables that are passed to it.
For example, consider the following call:
double percent = 10;
harry.raiseSalary(percent);
No matter how the method is implemented, we know that after the method call, the value of percent is still 10.
Let us look a little more closely at this situation. Suppose a method tried to triple the value of a method parameter:
public static void tripleValue(double x) // doesn't work { x = 3 * x; }
Let's call this method:
double percent = 10; tripleValue(percent);
However, this does not work. After the method call, the value of percent is still 10. Here is what happens:
-
x is initialized with a copy of the value of percent (that is, 10).
-
x is tripled—it is