A stack is a Last-In, First-Out linear data structure. The most recently added element is the first one to be removed.
The stack also refers to stack memory, a distinct area of RAM used for data storage. Other area is the Heap.
- Management: Handled by the compiler via stack pointers.
- Data Stored: Local variables, function parameters, and return addresses.
- Allocation: Contiguous blocks of memory. Allocation and deallocation are extremely fast because they only involve moving the stack pointer.
- Size: Fixed and limited (can lead to
StackOverflowError). - Lifetime: Variables are destroyed as soon as the function returns.
| Feature | Stack | Heap |
|---|---|---|
| Speed | Very Fast | Slower (overhead for searching blocks) |
| Access | Sequential | Random (via pointers) |
| Safety | High (automatic cleanup) | Low (potential for memory leaks/pointers) |
| Structure | Linear/Ordered | Hierarchical/Unordered |