×

Stack Program in Java

Stack Program in Java

The Stack class is part of the collection framework that inherits the Vector class. Thus, the Stack class can also be called a subclass of the Vector class. It implements the stack data structure that works on LIFO (Last In First Out) principle. The stack program in Java shows the usage of the stack in the program.

Syntax to Create a Stack

Stack<type> identifier = new Stack<type>();

type is the kind of object we are going to create, and identifier is the reference variable.

Adding Elements to the Stack

In order to add elements to the stack, the push() method is invoked. Consider the following program.

FileName: StackExample.java

 // Importing the class Stack
import java.util.Stack;
public class StackExample
{
// driver method
public static void main(String argvs[])
{
    // creating an object of the class Stack
    Stack<Integer> stk = new Stack<Integer>();
    // adding elements to the stack
    // stk contains 9
    stk.push(9);
    // stk contains 9, 5
    stk.push(5);
    // stk contains 9, 5, 7
    stk.push(7);
    // stk contains 9, 5, 7, 14
    stk.push(14);
    // stk contains 9, 5, 7, 14, 29
    stk.push(29);
    // caculating size of the stack
    int size = stk.size();
    // displaying the stack on the console
    System.out.println("The size of the stack is: " + size);
    System.out.println("The stack contains: " + stk);
}
} 

Output:

The size of the stack is: 5
The stack contains: [9, 5, 7, 14, 29] 

Explanation: The method push() adds elements to the stack. In the output, element 29 sits at the top of the stack since it is added at last, whereas element 9 is added at the beginning; therefore, element 9 sits at the bottom.

Removing Elements from the Stack

To remove elements from a stack, the pop() method is used. Observe the following program.

FileName: StackExample1.java

 // Importing the class Stack
import java.util.Stack;
public class StackExample1
{
// driver method
public static void main(String argvs[])
{
    // creating an object of the class Stack
    Stack<Integer> stk = new Stack<Integer>();
    // adding elements to the stack
    // stk contains 9
    stk.push(9);
    // stk contains 9, 5
    stk.push(5);
    // stk contains 9, 5, 7
    stk.push(7);
    // stk contains 9, 5, 7, 14
    stk.push(14);
    // stk contains 9, 5, 7, 14, 29
    stk.push(29);
    // caculating size of the stack
    int size = stk.size();
    System.out.println("The stack contains: " + stk);
    // removing the topmost element from the stack.
    for(int i = 0; i < size; i++)
    {
        int ele = stk.pop(); // for storing the popped element
        // displaying the popped element
        System.out.println("The popped element is : " + ele);
        // displaying the updated stack
        System.out.println("The stack contains: " + stk);
    }
    // checking whether the stack is empty or not
    if(stk.isEmpty())
    {
        System.out.println("\n The stack has now become empty.");
    }
}
} 

Output:

The stack contains: [9, 5, 7, 14, 29]
The popped element is : 29
The stack contains: [9, 5, 7, 14]
The popped element is : 14
The stack contains: [9, 5, 7]
The popped element is : 7
The stack contains: [9, 5]
The popped element is : 5
The stack contains: [9]
The popped element is : 9
The stack contains: []
The stack has now become empty. 

Explanation: In the following figure, we see that 29 is the topmost element. Therefore, when the pop() method is invoked, the topmost element gets removed, and the stack now looks like the following. Now, 14 has become the topmost element. Therefore, the next calling of the pop() method removes the element 14. Then, the next calling of the pop() method removes 7, and so on. At the end, the stack becomes empty.

Stack Implementation using LinkedList

We can also implement a stack using LinkedList. The following program does the same.

FileName: StackExample2.java

 // Importing the class LinkedList
import java.util.LinkedList;
public class StackExample2
{
// driver method
public static void main(String argvs[])
{
    // creating an object of the class LinkedList
    LinkedList<Integer> ll = new LinkedList<Integer>();
    // adding elements to the LinkedList
    // ll contains 9
    ll.add(9);
    // ll contains 9, 5
    ll.add(5);
    // ll contains 9, 5, 7
    ll.add(7);
    // ll contains 9, 5, 7, 14
    ll.add(14);
    // ll contains 0, 5, 7, 14, 29
    ll.add(29);
    // calculating size of the LinkedList
    int size = ll.size();
    System.out.println("The LinkedList contains: " + ll);
    // removing the topmost element from the LinkedList.
    for(int i = 0; i < size; i++)
    {
        int ele = ll.removeLast(); // for storing the removed element
        // displaying the removed element
        System.out.println("The popped element is : " + ele);
        // displaying the updated LinkedList
        System.out.println("The LinkedList contains: " + ll);
    }
    // checking whether the LinkedList is empty or not
    if(ll.isEmpty())
    {
        System.out.println("\n The LinkedList has now become empty.");
    }
}
} 

Output:

 The LinkedList contains: [9, 5, 7, 14, 29]
The popped element is : 29
The LinkedList contains: [9, 5, 7, 14]
The popped element is : 14
The LinkedList contains: [9, 5, 7]
The popped element is : 7
The LinkedList contains: [9, 5]
The popped element is : 5
The LinkedList contains: [9]
The popped element is : 9
The LinkedList contains: []
The LinkedList has now become empty. 

Explanation: By selecting the appropriate methods of the LinkedList class, the above program successfully imitates a stack. After the addition of elements, the linked list looks like the following

Stack Program In Java

If we see the top-down view, the list looks like the following:

Stack Program In Java

Now, element 29 sits at the top and 9 at the bottom. When the removeLast() method gets invoked, it removes the last element, i.e., element 29, from the list.

Stack Program In Java

Since, the removed element 29 is also the last element added to the list, we find that LIFO (Last-In-First-Out) principle is working properly. Now, element 14 occupies the topmost position. Therefore, on calling the removeLast() method removes element 14 from the list.

Stack Program In Java

Thus the removeLast() method keeps on removing the topmost element eventually, resulting in an empty list. We see that the LinkedList in the above program imitates a stack.

Note: We can even implement a queue from the above-mentioned doubly linkedList. The other top-down view gives the following.

Stack Program In Java

We see that element 9 is at the top of the stack. Therefore, if we start removing elements from the top, we end up following the FIFO (First-In-First-Out) approach. Because element 9 was added in the beginning. Then 5 got added after that 7 was added eventually 29 was added. During the removal of element 9 is removed; after that, element 5 is removed. Then, 7 is removed, and eventually, 29 is removed. Thus, the element that is added in the beginning is the first one that got removed and the element that was added at the end removed at the end. Thus, following the FIFO fashion which is nothing but a queue.

In the above code, replace the method removeLast() with removeFirst(), and the code starts behaving as a queue.


Related Topics

nth Prime Number in Java

A number is considered prime if only divisible by one and itself. Prime numbers include, for example, 2, 3, 5, 7, 11, etc. In looking at it another way, a...

5 minutes read.

Lambda expressions in Java

A brief introduction to Lambda expression in java In this topic, we will discuss the lambda expression in java. A lambda expression in Java is an enhanced version of an anonymous...

13 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Java Rename File

Renaming a file is the process of changing its name. Using the renameTo() function of the Java File class, renaming operations are possible. A file can be renamed using Java's renameTo()...

3 minutes read.

Collection Interfaces in Java with Examples

In this tutorial, we will discuss collection interfaces in Java with Examples. Introduction The Collection Interface is an individual from the Java Collections Framework. It is a root point of interaction of...

4 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Dutch National Flag Problem in Java

Dutch National Flag (DNF) is a programming issue that Edsger Dijkstra put up. The white, red, and blue hues make up the Dutch flag. The goal is to haphazardly set...

6 minutes read.

Find next greater number with same set of digits in Java

It contains a number (num). Finding the smallest number that has the same number of elements as num that is also larger than num is the task at hand. If...

8 minutes read.

How to override toString() method in Java?

Java is an object-oriented language. It only works with classes and objects. Thus, whenever we need to calculate, we need an object or objects that belong to the class. The Java method...

2 minutes read.

Java Integer toString() method

The toString() method of Java Integer class returns a String object which represents this Integer’s value. The second syntax returns a String object which represents the specified integer. The third syntax returns...

2 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

How to declare string array in Java

Introduction Array is a data structure with a fixed size, which allows us to store elements of similar type. Data of primitive types like int, char, float, string, etc. can be...

2 minutes read.

Java Wrapper Class

Wrapper class in Java encapsulates a primitive type within an object. In other words, it is a unique mechanism of Java to convert primitive type in to object and object into primitive type....

3 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Sleeping Barber Problem in Java

The barbershop in this issue has one barber, one barber chair, and N chairs for customers in the waiting area. We may demonstrate the issue by keeping with the original...

6 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

Creation of Multi Thread in java

What are threads in Java? We can use threads to facilitate parallel processing. Threads are helpful when you wish to execute several pieces of code concurrently. A thread is a small process...

3 minutes read.

Java Integer numberOfTrailingZeros() method

The numberOfTrailingZeros()  method of Java Integer class returns the total number of zero bits following the lowest-order one-bit in the 2’s complement binary representation of the specified int value. Syntax public static...

1 minute read.