How to use Java Stack with Examples


In the tutorial, Grokonez will introduce how to use Java Stack with Examples:

  • How does Java Stack work?
  • Hierarchy of Java Stack
  • Do push, pop, peek, search operations with Java Stack data structure

Related posts:
How to use Java PriorityQueue with Examples
How to use Java TreeMap with Examples

Java Stack

– Java Stack is a last-in-first-out (LIFO) data structure of objects. The usual push and pop operations are provided:


– Java Stack extends class Vector. See a hierarchy of Java Stack:


– Java Stack has just only one Constructor:

-> It creates an empty Stack.

– Java Stack implements five operations that allow a Vector to be treated as a Stack:

  • public boolean empty(): check a stack is empty or not
  • public E pop(): Removes the object at the top of a stack and returns that object as the value of this function.
  • public E peek(): get the object at the top of this stack but NOT removing it from the stack.
  • public E push(E item): Pushes an item onto the top of this stack
  • public int search(Object o): Returns the 1-based position from the top of the stack where the object is located; the return value -1 indicates that the object is not on the stack.

Java Stack with Integer Elements Example

In the following example, we create an integer stack that does a list operations:

  • Create a stack
  • Push elements to stack
  • Pop elements to stack
  • Check a stack is empty or NOT
  • Look an element in a stack

-> Example Code:

Java Stack with String Elements Example

Java Stack with User Defined Objects Example

– Create Developer class:

– For comparing 2 objects when using search operation of Java Stack, we need re-implement equals method:

– Now create a Developer Stack, when do a list operations on it:

-> Output:


We had learned how to use Java Stack with examples:

  • Understand about Java Stack’s Working Principle and Hierarchy
  • Create Java Stack Examples with Integer, String and User Defined Object

Happy Learning! See you later!

By grokonez | May 14, 2019.

Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *