next up previous
Next: Execution of a method Up: Unit 03 Previous: Example: use of static

Parameter passing

As said, the definition of a method contains in the header a list of formal parameters. Such parameters are used in the same way as variables inside the body of the method.

The call of a method contains the parameters that have to be used as arguments for the method. Such parameters are called actual parameters, to distinguish them from the formal parameters appearing in the header of the method definition.

When a method is called and thus activated, the actual parameters have to be bound to the formal parameters. In general, there are various ways of establishing such a binding. In Java, there is just one way: the so called call by value.

Let pa be an actual parameter in a method call, and pf the corresponding formal parameter in the header of the method definition: to bind pa to pf by value means to do the following, when the method is activated:

  1. The actual parameter pa is evaluated (notice that pa is in general an expression).
  2. A memory location is associated to the formal parameter pf.
  3. The value of pf (i.e., the corresponding memory location) is initialized with the value computed for pa.

In other words, the formal parameter pf behaves exactly as a local variable created the moment the method is called, and initialized with the value of the corresponding actual parameter pa.

At the end of the execution of the body of the method, the memory location reserved for the formal parameter is freed and the value stored in it is lost.

Note: The value of a variable that appears in the expression pa is not changed by the execution of the method. Note, however, that if such a value is a reference to an object, then the method can in fact change the object denoted by the reference (see later).

The following figure shows an example of parameter passing for the case where the parameter is a reference to an object. The case of parameters that are of a primitive data type will be described in Unit 4.

next up previous
Next: Execution of a method Up: Unit 03 Previous: Example: use of static