Stack Data Structure in Java

Stack Data Structure in Java

Data structures are ways of storing data on a computer. One of the simplest data structures is a Stack in a Java program! In this article, we will discuss the stack in java and its methods.

What is a Stack Data Structure?

A stack is a collection of elements stored in a Last-In-First-Out principle, just like getting a card from a deck or popping a candy out of a candy dispenser.

What are its methods?

The stack has two update methods and three accessor methods.

  1. Update Methods

    • push(e) – Adds element at the top of the stack.
    • pop( ) – Removes and returns the top element from the stack (or null if the stack is empty).
  2. Accessor Methods

    • top( ) – Returns the top element of the stack without popping the element
    • size( ) – Returns the number of elements in the stack.
    • isEmpty( ) – Returns a boolean indicating whether the stack is empty.

How to implement Stacks in Java?

Stack in Java program is used by calling the java.util.Stacks library.

import java.util.Stack;

Now declare your stack.

public static void main(String[]args){
      Stack<String> pupilNames = new Stack<>();

      pupilNames.push("Anna");
      pupilNames.push("Grace");
      pupilNames.push("John");
      pupilNames.push("Adam");
      pupilNames.push("Ben");

      System.out.println("Pupils entered the room: " + pupilNames);
 
      String lastPupil = pupilNames.pop();
      System.out.println("Last pupil entered the room: " + lastPupil);      


}
Pupils entered the room: [Anna,Grace,John,Adam,Ben]
Last pupil entered the room: Ben

About The Stack Data Structure In Java

Project Name:Stack Data Structure
Language/s Used:JAVA
Database:None
Type:Desktop Application
Developer:IT SOURCECODE
Updates:0
Stack Data Structure In Java– Project Information

Conclusion

Using this data structure is a good way to strengthen your source code and programming skills. For more information and references about data structures, check out callicoder.com and tutorialspoint.com

3 thoughts on “Stack Data Structure in Java”

Leave a Comment