next up previous
Next: Local variables Up: Unit 03 Previous: Execution of a method

Example: modification of an object done by a method

The following program shows what happens when passing parameters that are references to objects.

public class Parameters{
  public static void changeValueS (String s) {
    s = s.concat("*");
  }

  public static void changeValueSB (StringBuffer sb) {
    sb.append("*");
  }

  public static void main(String[] args) {
    String a = "Hello";
    StringBuffer b = new StringBuffer("Ciao");

    System.out.println("String a = " + a);
    changeValueS(a);
    System.out.println("String a = " + a);

    System.out.println("StringBuffer b = " + b.toString());
    changeValueSB(b);
    System.out.println("StringBuffer b = " + b.toString());
  }
}

The result of the execution of the program is the following:

String a = Hello
String a = Hello
StringBuffer b = Ciao
StringBuffer b = Ciao*

The actual parameters a and b are bound by value to the corresponding formal parameters s and sb, hence their value (i.e., the reference to the object) is not modified by the execution of the method. However, this does not mean that the state of the object they refer to cannot change (as shown by the example).

The reason why the state of the object referenced by b changes, while for a this is not the case, is not a direct consequence of parameter passing (note that the parameter is passed in the same way for a and b). The change depends on the use of the append() method, which modifies the state of the object on which it is invoked (i.e., sb, which refers to the same object as b, whereas the concat() method does not modify the state of the object s, and hence a).


next up previous
Next: Local variables Up: Unit 03 Previous: Execution of a method