next up previous
Next: Wrapper classes for the Up: Unit 04 Previous: Variables of primitive types

Methods that modify variables of primitive types

We have a similar difference in parameter passing, when we have a parameter of a primitive data type as opposed to a parameter of type reference to object. We will see next that passing parameters of type reference to object allows us to design methods that modify variables in the calling program unit, which is impossible if we pass directly primitive data types as parameters.

Suppose we want to write a method that modifies a variable of a primitive type (i.e., a method with side-effect on variables). For example, we try to implement a method that increments a variable of type int:

public static void increment(int p) {
  p = p + 1;
}
if we now invoke the increment method as follows:
public static void main(String[] args){
  int a = 10;
  increment(a);
  System.out.println(a);   // prints 10
}
we see that the program prints 10, instead of 11, as we could have expected. This is because, during the invocation of the increment method, the value 10 stored in the local variable a is copied in the formal parameter p. The increment method modifies the formal parameter p, but does not modify the content of the local variable a.

To obtain the desired effect, we can instead pass a variable that is a reference to an object that contains the integer:

public static void increment(MyInteger x) {
  x.a = x.a + 1;
}
where the class MyInteger, that acts as a wrapper of the integer, could simply be defined as follows:
class MyInteger {
  public int a;
}

This allows us to rewrite our program as follows:

public static void main(String[] args){
  MyInteger r = new MyInteger();
  r.a = 10;
  increment(r);
  System.out.println(r.a); // prints 11
}

Note that the value 10 is store in the instance variable a of the object MyInteger, which is referenced by r. The reference stored in the variable r is copied in the formal parameter x of the method increment when the method is invoked. Hence, x refers to the same object to which r refers, and the increment performed on the instance variable of such an object is visible also after the increment method has terminated.


next up previous
Next: Wrapper classes for the Up: Unit 04 Previous: Variables of primitive types