×

java · level 3 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.