Chapter 3 · Simulation

Pass-by-Value Lab

← Chapter 3
Java code
    Call stack
    Heap
    Output

    Pass-by-Value Lab

    Purpose: see what is copied when an argument is passed to a method in Java. Java always uses pass by value: the value of the argument is copied into the parameter. For primitive types this value is the number itself; for array, object and String variables it is the reference to the object on the heap. The object itself is not copied.

    How to use it

    1. Pick a program on the left. Use Step ▶ / ◀ Back (→ / ← on the keyboard), Play, Reset.
    2. In the middle is the call stack: main at the bottom and the frame of the running method at the top (highlighted). On the right is the heap: the arrays and objects created with new. An arrow from a reference variable goes to the object it points to; in the last step the changed value and arrow are highlighted.
    3. An object that no variable points to appears faded with a dashed outline: it is unreachable now and the garbage collector may reclaim it.
    4. While Try it yourself is on, you predict the result at some steps; the effect of the step appears after your answer.

    Things to remember

    • If a method assigns a new value to its parameter (x = …, d = new int[3], p = new Point()), only its own copy changes; the caller's variable is not affected.
    • If a method changes the object the reference points to (d[0] = 99, p.x = …), the caller sees the change too, because the two references point to the same object.
    • That is why a method that swaps two references cannot swap the caller's variables.
    • String is immutable: s + "!" creates a new object. A method can hand its result to the caller with return.

    Names such as @1, @2 are for display; real addresses depend on the JVM. The outputs of all programs were verified with javac --release 8 + java.

    Related slides: Chapter 3.2 · Methods.