☰ Contents How Java Runs

Methods and Memory

Student: Wait a minute. Show me that last memory diagram again?
Prof: This one?
Names (the stack)
main()
nums1 = @1001
nums2 = @1002
top level
Heap
@1001: [6, 7]
@1002: [999, 7]
Student: Yeah. What’s going on with the stack there?
Prof: Oh sharp eye! Right, so this is a program with a main method. That method is called to start the program. In this case, we didn’t have any definitions of values at the top level, so that’s empty. All the action is happening in main’s stack frame.
Student: Stack frame?
Prof: Every time a method is called, Java sets aside space for its parameters and its variables (the definitions in the method body) in what’s called a stack frame. So here we’re seeing that the two arrays were created inside main, which was called from the top level.
Student: Huh. OK. So that happens for all methods? Or is this just a main thing?
Prof: For all methods. It’s true even if we call some methods from the top level. For example if we have a builder pattern, there are some interesting aspects to the memory diagram:
Prof: So here we could talk about the memory diagram in the middle of running the builder loop. As in, what does memory look like when we are about to process the 3rd of the 4 elements in the array?
Names (the stack)
menu.discounted() on @1002
result = @1003
index = 2
p = 500
top level
regular = @1001
menu = @1002
Heap
@1001: [2000, 1000, 500, 800]
@1002: Menu[pricesCents=@1001]
@1003: [1800, 900, 0, 0]
Student: Wait, in the middle of the loop, what does that mean?
Prof: Well, Java runs code one step at a time, where “steps” are things like starting a method call, updating a variable, changing an array element, creating an object, and so on. So we can ask questions like “what does memory look like at a particular moment”.
Student: OK, and this picture is right after updating the array with 900.
Prof: That’s right. We could also talk about the memory diagram at the end of the program
Names (the stack)
menu.discounted() on @1002
result = @1003
index = 4
returns @1003
top level
regular = @1001
menu = @1002
sale = @1003
Heap
@1001: [2000, 1000, 500, 800]
@1002: Menu[pricesCents=@1001]
@1003: [1800, 900, 450, 720]
Prof: Now, Java may or may not actually keep track of the old stack frame like in this picture once the method call returns. But it’s a helpful picture!
Student: So that reference for the new array was made… inside the method?
Prof: That’s right!
Student: And then it gets stored at the top level?
Prof: In this example, that’s right.

Practice

Picture memory while big.area() is running, just before its return. Where is each name stored?

record Pizza(double inches, int costCents) {
  double area() {
    double radius = inches / 2;
    return radius * radius * Math.PI;
  }
}
String shop = "Trash Panda Pizza";
void main() {
  Pizza big = new Pizza(16, 1000);
  double bigArea = big.area();
  System.out.println(shop + ": " + bigArea);
}
shop
big
radius
inches