next up previous
Next: Example: modification of an Up: Unit 03 Previous: Parameter passing

Execution of a method

Consider the following method definition:

public static String duplicate(String pf) {
  return pf + ", " + pf;

Consider then the following main() method:

public static void main(String[] args) {
  String s;
  s = duplicate("pippo" + "&" + "topolino");

Let us analyze in detail what happens when the statement containing the call to the duplicate() method is executed:

  1. The actual parameters are evaluated.

    In our case, the actual parameter is the expression "pippo" + "&" + "topolino" whose value is the string "pippo&topolino".

  2. The method to be executed is determined by considering the name of the method, and the number and the types of the actual parameters. A method with a signature corresponding to the method call has to be found: the name of the method must be the same as in the call, and the formal parameters (i.e., their number and types) must correspond to the actual parameters.

    In our case, the method we are looking for must have the signature duplicate(String).

  3. The execution of the calling program unit is suspended.

    In our case, it is the method main().

  4. Memory is allocated for the formal parameters (considered as variables) and for the variables defined in the method (see later).

    In our case, memory is allocated for the formal parameter pf.

  5. Each formal parameter is initialized to the value of the corresponding actual parameter.

    In our case, the formal parameter pf is initialized to the reference to the object representing the string "pippo&topolino".

  6. The statements in the body of the called method are executed, starting from the first one.
  7. The execution of the called method terminates (either because the return statement is executed, or because there are no more statements to execute).

    In our case, the statement return pf + ", " + pf; is executed.

  8. The memory for the formal parameters and the local variables is freed, and all information contained therein is lost.

    In our case, the memory location corresponding to the formal parameter pf is freed.

  9. If the method returns a result, then the result becomes the value of the expression returned by the method invocation in the calling program unit.

    In our case, the result is "pippo&topolino, pippo&topolino".

  10. The execution of the calling unit continues from the point where it was suspended by the method call.

    In our case, the value "pippo&topolino, pippo&topolino" is assigned to the variable s.

next up previous
Next: Example: modification of an Up: Unit 03 Previous: Parameter passing