Program 21.4 Side Effects

There are two times when this does become important though. The first is with side effects. If you create an object a and then set b equal to a then changing some property of b changes that property of a also. a and b refer to the same space in memory. For example

import java.awt.Point;

public class RefTest {

  public static void main(String[] args) {
    Point a = new Point(3, 2);
    Point b = a;
    b.x = 33;
    b.y = -7;
    System.out.println(a);
  }

}
And herešs the somewhat surprising output:

% java RefTest
java.awt.Point[x=33,y=-7]
%
This program tried to print a but it looks like you got b instead. Thatšs because a and b are references to the object, not the object itself. When a was assigned to b, b was made to point to the same location as a. Therefore when the value of the object at that location changes, both and b change. This is true for any object at all in Java including arrays. It is not true for primitive data types like int, float or char.


Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
This Chapter
Examples
Home