Heap, Stack, GC Overview

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

Local variables and call chains are located on the thread stack. Objects are located on the heap and are released by the garbage collector when they become unreachable.

StackOverflowError: too deep calls. OutOfMemoryError: heap full.

Where used

Allocation pressure, escape analysis, GC pauses as a latency cause. Stack frames explain recursion limits; the heap explains object graphs and leaks.

Depth

Each thread manages call frames with local variables and return information on its stack. Objects are typically allocated in a shared memory area; local references can point to these objects. Therefore, a local variable does not automatically make the referenced object thread-local.

The garbage collector identifies objects that are no longer reachable from roots such as active stacks and static fields. It decides on memory release, not on the timely closing of external resources. Files and sockets therefore require explicit lifetime management.

Difficulty levels

  1. Distinguish between local reference and referenced object.
  2. Track reachability from GC roots.
  3. Separate memory cleanup and resource release.

Pitfalls

An object is not collected simply because a single reference goes out of scope. As long as another reachable path exists, it remains alive. System.gc is also not a reliable guarantee of release.

University approvals: 0
Tasks
Question 1

Where are Java objects typically located?

Question 2

A local variable references an object that is also located in a static field. What happens at the end of the method?

Question 3

Create an int array of length n and return its length.

Hint

An integer array is created with new int[n]. Its length is stored in the field .length, not in a method.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy