java · level 3 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
The keeps calls on the and objects on the .
javac turns your code into instructions for the JVM, the Java Virtual Machine, which runs them on any computer. The JVM splits memory in two. Each method call gets a frame on the stack, holding its own variables, cleared when the call returns.
Objects made with new live on the heap. A variable holds only a reference to its object, like an address. Passing it to a method copies the reference, not the object, so the method can change the object but cannot repoint your variable.
When nothing refers to an object any more, frees its memory, so you never free it yourself. The stack is smaller. A method that calls itself with no stopping point fills it with frames until the JVM gives up with StackOverflowError.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Runtime jvm = Runtime.getRuntime();
List<int[]> blocks = new ArrayList<>();
for (int i = 0; i < 20; i++) {
blocks.add(new int[250000]);
}
long usedMb = (jvm.totalMemory() - jvm.freeMemory()) / 1024 / 1024;
System.out.println("Holding 20 blocks, heap in use: about " + usedMb + " MB");
blocks = null;
System.gc();
System.out.println("Blocks released. The garbage collector may now free them.");
System.out.println("Processors available: " + jvm.availableProcessors());
}
} Memory numbers change from run to run, so a program that reports them is checked by pattern, not exact text.
guess first
What ends up in the suitcase? Guess first.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.util.ArrayList;
import java.util.List;
public class Main {
static void pack(List<String> bag) {
bag.add("passport");
bag = new ArrayList<>();
bag.add("sun cream");
}
public static void main(String[] args) {
List<String> suitcase = new ArrayList<>();
pack(suitcase);
System.out.println(suitcase);
}
}
your turn
Your turn. Report on the heap.
Memory in use is the total minus the free part. On line 5, call the Runtime method that reports the free part.
output
press run to see what happens
fix it
The stack overflows. Can you fix it?
output
press run to see what happens
- Java stops with
StackOverflowError. DoessumToever stop calling itself? - Each call asks for
sumTo(n - 1), past 0 and on forever, until the stack is full. - Add
if (n == 0) { return 0; }as the first line insidesumTo, then run.
nailed it
you know where your data lives. :D
- Method calls and their variables live on the stack.
- Objects live on the heap; variables hold references to them.
- Garbage collection frees objects that nothing points at.
new words in your collection
- JVM
- stack
- heap
- garbage collection
This lesson isn’t saved. A free account remembers every lesson you finish.