SE450: Basics: Values and References [33/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; }
}

Previous pageContentsNext page