Stack Class in Java

By | October 15, 2017

Let us learn what is Stack class in Java programming with its explanation, constructors, methods, implementation and output.

What is Stack Class?

The Stack class is a predefined class available in java.util package. This class implements a dynamic stack data structure.

A stack is basically an ordered list of elements with a similar data type, and stores elements within it. It is a linear data structure and works on LIFO (Last In First Out) principle.

Implementation of Stack Class in Java with Output, Code, Explanation

Image Source: Wikimedia

The Stack class in Java inherits from the Vector class. There are a handful of operations that can be performed on a stack which is enlisted below.

  1. Push: Inserting an element into the stack.
  2. Pop: Removing an element from the stack.
  3. Peek: Returning the element at the topmost index in the stack.
  4. Search: Searching an element in the stack.

The elements are inserted and deleted from the same end which is commonly known as TOP. So, the TOP is the reference pointer in a stack which helps to execute all the operations.

The element which is inserted as the last element gets removed as the first element since it gets stored at the TOP index. This is due to the LIFO structure.

A stack is said to be in an underflow state when it is completely empty and it appears to be in an overflow state when it is completely full.

 

Declaration of Stack Class

 

Constructors of Stack Class

SR. NO.CONSTRUCTORDESCRIPTION
1.Stack()This method constructs an empty stack.

Methods of Stack Class

SR. NO.METHODDESCRIPTION
1.boolean empty()This method checks if the stack is empty or not. If it is empty then it returns true, else false.
2.element pop()This method deletes the topmost element from the stack and returns it.
3.element push(element obj)This method inserts an element into stack starting from the topmost index and returns the element.
4.element peek()This method returns the topmost element from the stack without deleting or modifying it in any way.
5.int search(Object element)This method returns the position of the element available within the stack based on the element passed in the method parameter. If the element is not found then it returns -1.

Implementation of Vector Class in Java

Output

If you have any doubts about the implementation of Stack class in Java programming, let us know about it in the comment section. Find more on Oracle Docs.

Collection Frameworks
StringTokenizer Class
Vector Class
Random Class

Let's Discuss