SE450: Basics: Values and References [34/63] Previous pageContentsNext page

Java has a reference model for objects. This is like C# are different from C++. In C# terminology, Java objects are boxed, whereas base values are unboxed.

What does the following print?

file:Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
package basics.valref;
public class Main {
  private Main() {}
  static public void main (String[] args) {
    //stdlib.Trace.graphvizShowSteps (true); stdlib.Trace.run ();
    int vi = 27;  MutInt ri = new MutInt(42);
    int vj = vi;  MutInt rj = ri;
    vi += 1;      ri.plus(1);
    System.out.println(vi);
    System.out.println(vj);
    System.out.println(ri);
    System.out.println(rj);
  }
}
final class MutInt {
  private int v;
  public MutInt(int v) { this.v = v; }
  public String toString() { return "MutInt(" + v + ")"; }
  public void plus(int z) { v += z; }
}
trace-basics-valref-006-Main_main_8 trace-basics-valref-007-MutInt_plus_19 trace-basics-valref-008-Main_main_9

Consider the object diagram after line 00007:

   +--------------+      +-----------------+
   | i0 : MutInt  |      |  0 : Main.main  |
   | ------------ |      |  -------------  |
   +--------------+      +-----------------+
   |   v:int = 42 |      | vi:int = 27     |
   +--------------+      | vj:int = 27     |
                         | ri:MutInt = i0  |
                         | rj:MutInt = i0  |
                         +-----------------+

This phenomenon is called aliasing.

Note that aliasing occurs whenever an object is passed as an argument to a function.

Aliasing mutable values must be handled with care.

Previous pageContentsNext page