Implement a Stack Using an Array in Java

A stack is a limited version of an array. New elements or nodes as they are often Called, can be added to a stack and removed from a stack only from one end. For this reason, a stack is referred to as a LIFO structure (Last-In First-Out).

Mainly the following three basic operations are performed in the stack:

Push : adds a new node
Pop : removes a node

Stack (Last-In First-Out)

Additional primitives can be defined:

IsEmpty : reports whether the stack is empty
Peek : return the last element in the stack

Stack Implementation

Consider a stack class stores data in an array (static structure). The array reference type is Object[] which means that it can contain any kind of Java object.

When you run the program, the output will be:

Contents of Stack : 1 2 3 4 5 
Remove the top of stack element : 5
Return the top stack element : 4
Contents of Stack : 1 2 3 4 

Previous Post Next Post