Core Java and the Runtime Memory Model

References, the call stack and what == compares.

4 lessons · 3 past questions · 10 marks in the papers collected here

Open the interactive lessons →Core Java and the Runtime Memory Model past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Loops, step by step
  2. Arrays and references
  3. Activation records
  4. Same object or same value

1. Loops, step by step

Some loops look before they leap, and one leaps first.

when a loop body runs, and how nested counters carry over

A ticket gate can check your ticket before you walk through, or let you through and check at the exit. With an invalid ticket the first gate lets nobody in; the second has already let you in once.

A while loop is the first gate: test, then body. A do-while loop is the second: body, then test. A for loop is a while loop with the start value and the step written in its header. The gate picture stops at counting: the loop keeps whatever the body changed.

Why does it matter? When the condition is true at the start, both kinds behave alike. They differ exactly when it is false at the start, which is the case a question likes to set up in an inner loop.

Worked example: A false start

Problem.

n starts at 5 and both loops test n < 5. What prints?

public class Main {
    public static void main(String[] args) {
        int n = 5;
        while (n < 5) {
            System.out.println("while body " + n);
            n++;
        }
        do {
            System.out.println("do body " + n);
            n++;
        } while (n < 5);
        System.out.println("end " + n);
    }
}

What is asked.

All lines.

Idea.

Test before the first loop, run the body of the second before testing.

  1. while (n < 5): 5 is not below 5, so the body is skipped.
  2. do: the body runs, printing do body 5, and n becomes 6.
  3. The test 6 < 5 is false, so the loop stops.
  4. The last line prints end 6.

Answer.

do body 5, then end 6

Common mistake.

Skipping the do body because the condition is already false.

What if

The program prints do body 5 and end 6.

  • n starts at 4. What prints?
    It prints while body 4, do body 5, end 6.. The while runs once and leaves n at 5; the do body still runs once.
  • n starts at 9. How many lines, and what is the last?
    It prints do body 9 and end 10.. The do body does not look at the condition first.

Worked example: A counter that remembers

Problem.

k is declared outside both loops. What prints on one line?

public class Main {
    public static void main(String[] args) {
        int k = 0;
        for (int row = 0; row < 3; row++) {
            while (k < row * 2) {
                System.out.print(k);
                k++;
            }
            System.out.print("|");
        }
    }
}

What is asked.

The line.

Idea.

Keep one row per outer round and carry k forward.

  1. row = 0: the inner test 0 < 0 is false, so only | is printed.
  2. row = 1: k runs while below 2, printing 01, then |.
  3. row = 2: k is already 2 and runs while below 4, printing 23, then |.

Answer.

|01|23|

Common mistake.

Restarting k at 0 in every outer round.

Where the counter lives

Outside

int k = 0;
for (int r = 0; r < 3; r++) {
    while (k < r) k++;
}

Inside

for (int r = 0; r < 3; r++) {
    int k = 0;
    while (k < r) k++;
}

The difference. The line that declares k has moved.

A variable declared inside a loop body is new in every round; one declared outside keeps its value.

When this breaks

"A for loop body runs at least once" is false. If the condition fails at the start, the body never runs and the step expression never runs either.

2. Arrays and references

Methods get copies; sometimes the copy is an arrow.

what a method receives when you pass an array or a number

Give a friend a copy of your house key. If they paint the wall, your wall is painted. If they throw their key away and cut a key to another house, your key still opens your house.

An array variable is such a key. Passing it to a method copies the key, not the house. The analogy stops at plain numbers: an int variable holds the number itself, so the method gets a separate number.

Why is there no way to move the caller's arrow? The parameter is a new variable inside the method's own memory. Assigning to it changes that variable only.

Worked example: Write, then replace

Problem.

What do the two print lines show?

public class Main {
    static void bump(int[] data) {
        data[0] = data[0] + 10;
    }
    static void swapOut(int[] data) {
        data = new int[] {99};
        data[0]++;
    }
    public static void main(String[] args) {
        int[] v = {1, 2};
        bump(v);
        System.out.println(v[0]);
        swapOut(v);
        System.out.println(v[0] + " of " + v.length);
    }
}

What is asked.

Two lines.

Idea.

Separate writes into the array from assignments to the parameter.

  1. bump writes into the shared array, so v[0] becomes 11.
  2. swapOut assigns a new array to its parameter data.
  3. The increment changes the new array only.
  4. v still refers to the first array: element 11, length 2.

Answer.

11, then 11 of 2

Common mistake.

Believing swapOut replaces v.

Passing an array to a method

  1. v holds a reference to one array object on the heap.
  2. The call copies the reference into data. Now two names reach one array.
  3. Writing through data changes the shared array, so the caller sees 11.
  4. Assigning to data moves only that local arrow to a new array. v is not touched.
  5. This write lands in the new array only.
  6. The method's record is gone. v still reaches the first array, which holds 11 and 2.
What if

The program prints 11 and 11 of 2.

  • swapOut returns the new array and main writes v = swapOut(v);. What is the second line?
    It prints 100 of 1.. Now the caller itself moves its arrow to the returned array.
  • main calls bump(v.clone()); instead of bump(v);. What prints?
    It prints 1 and 1 of 2.. bump writes into a separate copy.

Worked example: A number, an alias, a new arrow

Problem.

What are the three values?

public class Main {
    static void raise(int x) {
        x = x + 1;
    }
    public static void main(String[] args) {
        int score = 4;
        raise(score);
        int[] p = {4};
        int[] q = p;
        q[0] = 7;
        q = new int[] {0};
        System.out.println(score + " " + p[0] + " " + q[0]);
    }
}

What is asked.

One line.

Idea.

A number is copied; an array arrow is shared until one side moves.

  1. raise changes its own copy of 4, so score stays 4.
  2. q is an alias of p; writing q[0] = 7 changes the shared array.
  3. q then moves to a new array holding 0.
  4. p still sees 7.

Answer.

4 7 0

Common mistake.

Letting the last assignment to q affect p.

Into the box or move the arrow

Write into it

static void f(int[] d) {
    d[0] = 5;
}

Reassign

static void f(int[] d) {
    d = new int[] {5};
}

The difference. An index on the left of = against the bare name.

The caller sees writes into the shared object, never a reassigned parameter.

When this breaks

"clone() gives an independent array" fails for an array of arrays. The copy is only one level deep: both outer arrays still point at the same rows until one is replaced.

A shallow grid copy

public class Main {
    public static void main(String[] args) {
        int[][] g = { {1, 2}, {3} };
        int[][] h = g.clone();
        h[0][0] = 50;
        h[1] = new int[] {60};
        System.out.println(g[0][0] + " " + g[1][0]);
    }
}

3. Activation records

Every unfinished call keeps its own notes.

the memory each method call gets, and the order calls finish

You are reading a book, stop to look up a word, and while reading the entry stop again to check a symbol. You finish the newest task first and then go back to the one under it. Each paused task needs a bookmark.

A method call is a task and its bookmark is the activation record. The course lists what it holds: parameters, local variables, a control link, a return address and a return-value link. The bookmark picture stops at one point: a record also holds the task's own variables, not only the place.

Why a stack? A caller cannot continue until its callee returns, so the call made last always ends first. That last-in, first-out order is exactly what a stack gives.

Inside one record

PartAnswers
parameterswhat was passed in?
local variableswhat has this call computed?
control linkwhose record is below mine?
return addresswhere does the caller continue?
return-value linkwhere does my result go?

Worked example: Two calls deep

Problem.

What prints, and how many records exist at the deepest point?

public class Main {
    static int add(int a, int b) {
        return a + b;
    }
    static int twice(int n) {
        int r = add(n, n);
        return r;
    }
    public static void main(String[] args) {
        System.out.println(twice(6));
    }
}

What is asked.

The number and the depth.

Idea.

Push at each call, pop at each return.

  1. main calls twice(6): two records.
  2. twice calls add(6, 6): three records.
  3. add returns 12 and its record is removed.
  4. twice returns r, and main prints 12.

Answer.

12, with at most three records

Common mistake.

Counting only recursive calls as new records.

Records push and pop

  1. main has the only record. It is about to call twice(6).
  2. A new record holds the parameter n, the local r and the way back to main.
  3. add gets its own record on top. twice is paused below it.
  4. add returns 12. Its record is popped and the value is stored in r.
  5. twice returns 12 to main, which prints it. One record remains.

Worked example: Work on the way back

Problem.

sumTo prints after its recursive call. What is the output?

public class Main {
    static int sumTo(int n) {
        if (n == 0) {
            return 0;
        }
        int below = sumTo(n - 1);
        System.out.println("back in " + n);
        return below + n;
    }
    public static void main(String[] args) {
        System.out.println("total " + sumTo(3));
    }
}

What is asked.

All lines.

Idea.

Go down until the stopping case, then print while popping.

  1. sumTo(3) calls sumTo(2), then sumTo(1), then sumTo(0), each in a new record with its own n.
  2. sumTo(0) returns 0 without printing.
  3. The record for 1 resumes: it prints back in 1 and returns 1.
  4. Then 2 prints and returns 3; then 3 prints and returns 6.
  5. main prints total 6.

Answer.

back in 1, back in 2, back in 3, total 6

Common mistake.

Printing 3 first because it was called first.

What if

sumTo(3) prints back in 1, back in 2, back in 3, total 6.

  • The print moves above the line with the recursive call. In what order do the three lines print?
    It prints back in 3, back in 2, back in 1, total 6.. Each call now speaks while the stack is growing.
  • The if that returns 0 is deleted. How does the program end?
    It compiles, then fails with StackOverflowError.. Records are pushed with no call ever returning, until the stack is full.
When this breaks

"A record disappears when its variables are no longer used" is false. It stays until the call returns or an exception leaves the method.

4. Same object or same value

Two things can look alike without being one thing.

what == answers for text and boxed numbers

Two identical bus tickets say the same thing but are two pieces of paper. Two friends reading one poster look at the same piece of paper. "Same words" and "same paper" are different questions.

equals asks about the words. == between objects asks about the paper. Java saves memory by sometimes handing out the same paper: equal string literals are interned. The analogy stops there, because you must know exactly when sharing is guaranteed.

Why only sometimes? A literal is known to the compiler, so one pooled object can serve every use. new String asks for a fresh object. Text joined from a variable is built while the program runs, so it is a new object too.

Worked example: Four ways to ask about tea

Problem.

Predict the four lines.

public class Main {
    public static void main(String[] args) {
        String a = "tea";
        String b = "tea";
        String c = new String("tea");
        String half = "te";
        String d = half + "a";
        System.out.println(a == b);
        System.out.println(a == c);
        System.out.println(a == d);
        System.out.println(a.equals(d));
    }
}

What is asked.

Four boolean values.

Idea.

Draw where each string object comes from.

  1. a and b use one literal, so a == b is true.
  2. c was made with new: another object, false.
  3. d was joined at run time from a variable: another object, false.
  4. a.equals(d) compares the letters: true.

Answer.

true, false, false, true

Common mistake.

Answering from the letters alone.

What if

The program prints true, false, false, true.

  • half is declared final. What is the third line?
    It prints true.. A final variable with a literal value makes half + "a" a constant the compiler can compute and intern.
  • The third test becomes a == d.intern(). What is the third line?
    It prints true.. intern() returns the pooled object with those letters.

Worked example: Boxes small and large

Problem.

Predict the four lines.

public class Main {
    public static void main(String[] args) {
        Integer x = 100, y = 100;
        Integer p = 500, q = 500;
        int raw = 500;
        System.out.println(x == y);
        System.out.println(p == q);
        System.out.println(p.equals(q));
        System.out.println(p == raw);
    }
}

What is asked.

Four boolean values.

Idea.

Small boxes are shared; a plain int forces a number comparison.

  1. 100 lies between -128 and 127, so both variables get the shared box: true.
  2. 500 is outside that range; on this JDK two boxes are made: false.
  3. equals compares the numbers: true.
  4. raw is an int, so p is unboxed and the numbers match: true.

Answer.

true, false, true, true

Common mistake.

Concluding from the small case that == compares boxed values.

One declaration, one answer

Two boxes

Integer a = 900;
Integer b = 900;
boolean s = a == b;

A box and a number

Integer a = 900;
int b = 900;
boolean s = a == b;

The difference. The declared type of b.

Two references compare identity; a reference and a primitive compare values.

When this breaks

A test with small numbers proves nothing about large ones. The language guarantees shared boxes from -128 to 127; outside that range it promises nothing, and the default on this JDK gives separate objects.

Practise this topic →

Weeks covering this topic

Other Java topics