Array Based Stack Implementation in Java

LEVEL: Intermediate

Whats in this post?

  1. Code
  2. Output (not available)
  3. Background and Explanation of the code


To copy code: Click  “View Source” on the right of this code snippet.

Background and Explanation of the code

Here we assume in current article, that stack‘s capacity is limited to a certain value and overfilling the stack will cause an error. Though, using the ideas from dynamic arrays implementation, this limitation can be easily avoided.

In spite of capacity limitation, array-based implementation is widely applied in practice. In a number of cases, required stack capacity is known in advance and allocated space exactly satisfies the requirements of a particular task. In other cases, stack’s capacity is just intended to be “big enough”. Its capacity is quite large, but too deep recursion still may result in stack overflow.

Implementation of array-based stack is very simple. It uses top variable to point to the topmost stack’s element in the array.

  1. Initialy top = -1;
  2. push operation increases top by one and writes pushed element to storage[top];
  3. pop operation checks that top is not equal to -1 and decreases top variable by 1;
  4. peek operation checks that top is not equal to -1 and returns storage[top];
  5. isEmpty returns boolean (top == -1)