liveBook · Manning

Heap

As explained in 100 Java Mistakes and How to Avoid Them

The heap is the runtime memory area from which dynamically allocated objects and data structures are allocated.

A heap is the runtime memory area used for dynamically allocated objects and data structures. In recursive algorithms, moving intermediate call state into a heap-resident collection can replace a stack-depth limit with a heap-size limit. section 5.4.1

Use heap-backed state when recursion may become unusually deep:

  • Rewrite tail recursion as a loop when possible; this avoids accumulating recursive stack frames. section 5.4.1
  • For non-tail recursion, store pending nodes or call state in an ArrayDeque or another side collection. section 5.4.1
  • Expect the iterative version to be longer, and preserve every variable needed between recursive calls. section 5.4.1

Iterative tree traversal

A recursive tree search can overflow on very deep trees. An iterative search keeps nodes to visit in a Deque, allowing traversal depth to be limited by heap capacity rather than stack capacity. section 5.4.1

Node find(String name) {
  Deque<Node> stack = new ArrayDeque<>();
  stack.add(this);
  while (!stack.isEmpty()) {
    Node node = stack.pollLast();
    if (node.name().equals(name)) return node;
    Collections.addAll(stack, node.children());
  }
  return null;
}

Shows a Java tree search that replaces recursive calls with an ArrayDeque-backed traversal stack. section 5.4.1

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Contrasts recursive stack usage with iterative heap storage and stops short of general heap-management internals.
Examples
Demonstrates deep string processing, tail-recursion conversion, and iterative search through a named tree.
What it assumes
Assumes familiarity with recursive calls, stack depth, loops, collections, and Java methods.
What you can do after
Apply it via ArrayDeque to refactor recursive traversals that may exceed stack capacity.
How it connects
Connects heap with recursion, call stacks, iteration, tree traversal, collections, and Java records.

Also explained in

Compare how 7 books explain heap →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.