Stack frames and objects (like the Idea Lab activity): Correct Solution
Given the code below, this method call:
Jance.foad();
...will eventually reach the point marked HERE. Draw a diagram of the stack and the heap at that point.
(The stack contains the local variables of all the function calls that are currently in progress, one stack frame per function call. The heap contains all of the objects that currently exist.)
In your diagram:
- Label each stack frame with the name of the method.
- Label each object with the name of its class.
- Include the names of all the variables that belong to each object and stack frame, including the implicit
this parameter if present. (You do not need to write the types of any variables.)
- When a variable's value is null or a primitive, write the value immediately next to the variable.
- When a variable points to an object, draw an arrow from the variable to the object it points to.
The code:
public class Jance {
private int soel;
Jance(int soel) {
this.soel = soel;
}
public static void foad() {
Stecs ia = new Stecs(729);
HERE;
}
}
public class Stecs {
private int cac;
Stecs(int cac) {
this.cac = cac;
}
}
Solution
Hints for practicing this puzzle:
- Practice with difficulty 0, then work your way up. This will help you get a handle on what the puzzle is asking.
- There is only one path through the code from the starting method call to HERE. Start by finding that path.
- Be thorough. Double check that you've fully diagrammed each step before you move on to the next one.
- You can feed this code into https://pythontutor.com and watch a diagram like this build up step by step. (Yes, despite the web site's name, it also works with Java.)
Related puzzles: