This post is completed by 1 user

  • 0
Add to List

362. Stack Java Class - Explained

Earlier we saw about Stack and its implementation using Linked List. Java has a built in class for Stack. In this article we will discuss about it in detail. First brief about Stack.

What is Stack??

  • Stack is an abstract data type (ADT) and very useful in programming.
  • In computer science, a stack is an abstract data type that serves as a collection of elements.
  • Majorly all the operations are done at only one end of the stack which is top of the stack.
  • The order in which elements in stack are stored is with LIFO (Last-in-First-Out) manner. This means the element inserted last will be removed first.

See the diagram below for more understanding.

Stack Operations

Operations on Stack

push(): Push the element to the top of the Stack. Time- O(1)

pop(): Remove the element from the top of the stack and returns that element. Time- O(1)

peek(): Returns the top element of the stack without removing it. Time- O(1)

isEmpty(): Return true or false, based on stack is empty or not. Time- O(1)

getSize(): Return the size of the stack. Time- O(1).


Inserting 1 into Stack.
Inserting 2 into Stack.
Inserting 3 into Stack.
Popping Element from stack
Popped Element: 3
Popping Element from stack
Popped Element: 2
Inserting 6 into Stack.
peeking Element from stack
Peeking Element: 6
[1, 6]
Is Stack Empty: false
Stack Size: 2
Stack Size: 2
Searching element 5 in Stack
5 not found in Stack
Searching element 1 in Stack
1 found in Stack at position: 2