Stack implementation in Java

A stack is a linear data structure which follows the LIFO (last-in first-out) principle. That means the objects can be inserted or removed only at one end of it also called as top.


The stack supports below core operations –

  • push Pushes an item onto the top of the stack (i.e. above its current top element).
  • pop Removes the object at the top of the stack and returns that object from the function. The stack size will be decremented by one.
    Data stack
  • isEmpty Tests if the stack is empty or not.
  • isFull Tests if the stack is full or not.
  • peek Returns the object at the top of the stack without removing it from the stack or modifying the stack in any way.
  • size Returns the number of elements present in the stack.

Stack can easily be implemented as array. Below is the Stack implementation in Java using an array.


Download   Run Code


Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
Top element is: 3
Stack size is 1
Removing 3
Stack Is Empty


The time complexity of push(), pop(), peek(), isEmpty(), isFull() and size() is constant. i.e. O(1).



Stack is also included in Java’s collection framework.


Download   Run Code


Top element is: D
Stack size is 2
Stack is not Empty

1 Star2 Stars3 Stars4 Stars5 Stars (2 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of