Stack Heap and Class Design
Applied class exercises for week 3, covering 2026-03-12-object-oriented-programming-ii and reinforcing java-mutability (why reference types behave differently from primitives when passed to methods). The class has two halves: sketching the runtime call stack and object heap to explain reference behaviour, and using that same “an object is a thing with fields” view to argue for a better class design.
On the HTML site, fill in each blank with your answer (as a quoted string, e.g. "1"), then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).
How to draw a stack/heap sketch
The sketches use a fixed vocabulary. Learn it before attempting the questions, because it is the form the answers are expected in:
- a stack frame is the method’s name in bold above a two-column table, one row per local — parameters count as locals and get a row;
- a primitive value is written straight into the value cell (
3,0,1); - a reference is a filled dot in the value cell, with a black arrow to the object it names;
- a heap array is a plain box holding the array literal, e.g.
{3, 2, 3}; - a heap object is a box with the class name in a bold header and one name/value row per field;
- frames whose call has already returned are greyed out, and it is not necessary to include them at all;
- frames are stacked with
mainat the top and each deeper call beneath it.
Two aliases pointing at one box is the whole point of the notation: it is what makes “the same object seen through two names” visible on paper.
The warm-up: aliasing an array
The whole exercise is motivated by a function whose return value surprises people:
static int[] reverse() {
int[] first = {1, 2, 3};
int[] second = first;
int last = first[2];
second[0] = last;
second[1] = first[1];
second[2] = first[0];
return second;
}This returns {3, 2, 3}, not {3, 2, 1}.
Figure 1: The stack and heap for the warm-up reverse() function. One stack frame, four rows, and a single heap array: first, second and the returned value are three names for one box, which is why writing through second is visible when read back through first. A filled dot with a black arrow is a reference; a primitive’s value is written in its cell.
int[] second = first; copies the reference, not the array. So there is exactly one array on the heap, and the three assignments all write into it:
| step | array afterwards |
|---|---|
last = first[2] |
{1, 2, 3}, last == 3 |
second[0] = last |
{3, 2, 3} |
second[1] = first[1] |
{3, 2, 3} (writes 2 over 2) |
second[2] = first[0] |
{3, 2, 3} — first[0] is now 3, not the original 1 |
The last line is where the aliasing bites: by the time it runs, first[0] has already been overwritten. If second were an independent copy, the last line would read the untouched 1 and the function would return {3, 2, 1}, an actual reverse.
Question 1 — Tracing the call stack and heap
Understanding the runtime call stack and object heap clarifies unexpected behaviour of reference types. Consider:
class Counter {
private int number;
public Counter() { this.reset(); }
public void increment(int amount) { this.number += amount; }
public void increment() { this.number++; }
public void reset() { this.number = 0; }
public int getValue() { return this.number; }
}
class DebugMe {
static void f(Counter counter, int param) {
counter.increment();
param++;
}
public static void main(String[] args) {
Counter first = new Counter();
int second = 0;
f(first, second);
System.out.println(first.getValue());
System.out.println(second);
}
}Task 0 is to sketch the state of the call stack and heap just before f finishes executing; Task 1 is to say what main prints.
What does main print (first line, then second line)?
First line →
Second line →
Figure 2: Task 0’s answer: the state just before f returns. main sits above f; args and first hold references (dots) into the heap, second holds the primitive 0. first and counter point at the SAME Counter object, whose number field already reads 1. The increment frame is greyed because that call has already returned; such frames need not be drawn at all.
Read the answer straight off the picture:
firstandcounterare two references to oneCounterobject.counter.increment()insidefmutates that shared object, so the change is visible throughfirstafterfreturns —first.getValue()prints1.paramis anint, passed by value.param++incrementsf’s own copy (the frame showsparamat1) and leavesmain’ssecondat0— so the second line prints0.
That is the general rule this class exists to fix in place: mutating an object through a reference parameter is visible to the caller; reassigning or incrementing a primitive parameter is not. (Reassigning a reference parameter — counter = new Counter() inside f — would likewise be invisible to main; Java passes the reference itself by value.)
args still gets a row and still points at a heap array, drawn {} because the program was run with no command-line arguments.
Question 2 — Designing a Vertex class
The Triangle class represents a triangle as a 2D array of coordinates: vertexes[0] is the three x-coordinates, vertexes[1] the three y-coordinates.
Figure 3: The triangle the exercise is about: vertices A, B, C with the interior angles alpha, beta, gamma and the sides a, b, c opposite them, beside the matrix form of the representation - one row of x-coordinates over one row of y-coordinates, which is exactly the double[][] the Triangle class stores.
The three-double constructor takes the side lengths \(a\), \(b\), \(c\) of Figure 3, not coordinates, and places the triangle in the plane for you:
public class Triangle {
private double[][] vertexes;
private static double square(double number) {
return number * number;
}
public Triangle(double a, double b, double c) {
double dividend = (square(a) - square(b) - square(c));
double cx = dividend / (-2 * c);
double cy = Math.sqrt(square(b) - square(cx));
// the above just calculates the position of a third vertex
// you do not need to understand it
this.vertexes = new double[][]{
// array of x-coordinates
new double[]{0, c, cx},
// array of y-coordinates
new double[]{0, 0, cy}
};
}
public Triangle(double[][] vertexes) {
this.vertexes = vertexes;
}
private double distance(double x1, double x2, double y1, double y2) {
return Math.sqrt(square(x1 - x2) + square(y1 - y2));
}
public double perimeter() {
double x0 = vertexes[0][0];
double x1 = vertexes[0][1];
double x2 = vertexes[0][2];
double y0 = vertexes[1][0];
double y1 = vertexes[1][1];
double y2 = vertexes[1][2];
return distance(x0, y0, x1, y1) + distance(x1, y1, x2, y2)
+ distance(x2, y2, x0, y0);
}
public Triangle scale(double multiplier) {
double[][] scaledUp = new double[2][3];
for (int x = 0; x < 2; x++) {
for (int y = 0; y < 3; y++) {
scaledUp[x][y] = vertexes[x][y] * multiplier;
}
}
return new Triangle(scaledUp);
}
}Design a Vertex class (signatures only, no implementation needed) that could simplify this — a triangle is really a collection of three vertices, each with an x and a y coordinate.
Only the signatures are designed, in shorthand: name, parameter types without parameter names, and a trailing comment.
class Vertex {
Vertex(); // Construct a new vertex at (0, 0)
Vertex(double, double);
double distance(Vertex); // distance to another vertex
Vertex scale(double); // multiply the coordinates by the given amount
}Triangle is then rewritten on top of it. Either a Vertex[] or three Vertex member variables would do; the version below takes the second option, even though the question phrases the constructor as Triangle(Vertex[]):
public class Triangle {
private Vertex a;
private Vertex b;
private Vertex c;
public Triangle(double a, double b, double c) {
double dividend = (square(a) - square(b) - square(c));
double cx = dividend / (-2 * c);
double cy = Math.sqrt(square(b) - square(cx));
this.a = new Vertex();
this.b = new Vertex(c, 0);
this.c = new Vertex(cx, cy);
}
public Triangle(Vertex a, Vertex b, Vertex c) {
this.a = a;
this.b = b;
this.c = c;
}
public Triangle(double[][] vertexes) {
this.a = new Vertex(vertexes[0][0], vertexes[1][0]);
this.b = new Vertex(vertexes[0][1], vertexes[1][1]);
this.c = new Vertex(vertexes[0][2], vertexes[1][2]);
}
public double perimeter() {
return a.distance(b) + b.distance(c) + c.distance(a);
}
public Triangle scale(double multiplier) {
return new Triangle(a.scale(multiplier), b.scale(multiplier),
c.scale(multiplier));
}
}perimeter() collapses from six local variables and three four-argument calls to one line, and scale from a nested loop over anonymous indices to one call per vertex. Introducing Vertex moves the x/y bookkeeping into a single-responsibility class, so Triangle’s own methods read as “distance between vertices” and “scale each vertex” rather than juggling raw array indices — the cohesion argument taken up properly in java-cohesion-and-coupling.
Two things about the original listing:
- The three-argument constructor is the law of cosines. With \(\mathcal{A}\) at the origin and \(\mathcal{B}\) at \((c, 0)\),
cx\(= (b^2 + c^2 - a^2) / 2c = b\cos\alpha\) andcy\(=\sqrt{b^2 - cx^2}\), i.e. \(\mathcal{C}\)’s coordinates. \(\mathcal{A}\) is at \((0,0)\), and the code writesnew double[]{0, c, cx}for the x row, so \(\mathcal{B}\) has y-coordinate 0 and x-coordinatec. perimeter()does not actually compute the perimeter.distanceis declared(double x1, double x2, double y1, double y2)— both x’s, then both y’s — but every call passes coordinates point-wise:distance(x0, y0, x1, y1)bindsx2toy0andy1tox1, so the result is \(\sqrt{(x_0 - y_0)^2 + (x_1 - y_1)^2}\). That is a live bug, and it is caused by exactly the thing the exercise is arguing against: an argument list of four baredoubles carries no information about which number is an x and which is a y. TheVertexrewrite makes the same mistake impossible to write, becausea.distance(b)has nowhere to put a coordinate in the wrong slot.
Question 3 — Recursive call stack (bonus)
class Reverser {
static void reverse(int[] arr) {
int n = arr.length;
if (n == 1) {
return;
}
// copy [1..n - 1] into rest
int[] rest = new int[n - 1];
for (int i = 1; i < n; i++) {
rest[i - 1] = arr[i];
}
arr[n - 1] = arr[0];
reverse(rest);
}
public static void main(String[] args) {
int[] numbers = {42, 24, 11};
reverse(numbers);
}
}Sketch the state of the call stack and heap just prior to the third call to reverse.
“Just prior to the third call” means two reverse frames are already live and neither has returned, so all three frames are drawn solid:
Figure 4: Task 4’s answer: the stack and heap immediately before the third call to reverse. Three live frames, four heap arrays. Each call’s rest becomes the next call’s arr - which is why the second and third boxes each have two arrows into them - while main’s numbers and the first call’s arr are two names for one array that has already been written to.
Reading the trace off the figure:
| call | arr on entry |
rest built |
arr[n-1] = arr[0] leaves arr as |
|---|---|---|---|
| 1st | {42, 24, 11} |
{24, 11} |
{42, 24, 42} |
| 2nd | {24, 11} |
{11} |
{24, 24} |
| 3rd | {11} |
— (n == 1, returns) |
{11} |
Two structural points the picture makes:
restis a fresh array each time.main’snumbersand the first call’sarrare the same box (one arrow each into{42, 24, 42}), but every deeper call works on a copy. Only the top frame’s write ever reachesnumbers.Reverser.reversedoes not reverse anything. Aftermainreturns,numbersis{42, 24, 42}— the42has been copied over the11and nothing has moved. Each call writes its own first element into its own last slot and then hands a copy to the next call, so every write below the first frame lands in an array nobody keeps a reference to. The call stack sketch is what makes that visible; reading the source alone, the recursion looks plausible.
The base case is n == 1, so an empty array never terminates it — reverse(new int[0]) reaches new int[n - 1] with n == 0 and throws NegativeArraySizeException. A base case of n <= 1 would be the safer guard, the same widening move the week 5 practical makes for RecursiveFibonacci — see week5-lab-debugging.