CSC300 / CSC402: Assignment and Parameters with Object Types [15/24] Previous pageContentsNext page

Very Important!

Assignment, or passing a reference to an object of some type to a method with an object type parameter results in copying the address of the object to a new place in memory.

This includes boxed types, arrays, and any other object for which a class is defined. Modifying the data in the object (if the object is mutable) affects what the calling code "sees".

06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
static class MyInteger {
    int value;
    MyInteger(int value) {
        this.value = value;
    }
    void add(int value) {
        this.value += value;
    }
    void multiply(int value) {
        this.value *= value;
    }
}

public static void main (String[] args) {
    Trace.showBuiltInObjects (true);
    Trace.drawStepsOfMethod("f");
    Trace.run ();
    MyInteger x = new MyInteger(35);
    MyInteger y = x;
    Trace.draw();
    y.add(10);
    y = f(y);
}

public static MyInteger f(MyInteger y) {
    y.multiply(10);
    return y;
}
002-Reference-Hello_f_32

Note: The variable y in the main program is simply an alias for the object also referenced by the variable x.

The variable y in the function f is pointing at the same object (although we wouldn't call it an alias here)!

Previous pageContentsNext page