Java Program to Implement stack data structure

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java program to implement Stack

Output

Inserting 1
Inserting 2
Inserting 3
Stack: 1, 2, 3,  
After popping out
1, 2, 

In the above example, we have implemented the stack data structure in Java.

To learn more, visit Stack Data Structure.


Example 2: Implement stack using Stack class

Java provides a built Stack class that can be used to implement a stack.

Output

Stack: [Dog, Horse, Cat]
Stack after pop: [Dog, Horse]

In the above example, we have used the Stack class to implement the stack in Java. Here,

  • animals.push() - insert elements to top of the stack
  • animals.pop() - remove element from the top of the stack

Notice, we have used the angle brackets <String> while creating the stack. It represents that the stack is of the generic type.