×

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

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

How to Convert Decimal to Hexadecimal in Java

How to Convert Decimal to Hexadecimal in Java The hexadecimal number uses 16 values to represent a number. Numbers from 0 to 9 represented by digits and the numbers from 10...

3 minutes read.

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes,...

3 minutes read.

Java String Inbuilt functions

There are different types of inbuilt functions available in the Java String class, all of them are listed below. Char chat At (int index)It outputs the character indicated by the index....

5 minutes read.

Timestamp Operation in Java

JDBC escape syntax is supported by Timestamp's formatting and parsing functions. Additionally, it adds support for fractional seconds values for SQL TIMESTAMP.java.util.Date is wrapped in a lightweight wrapper that enables...

3 minutes read.

HashMap Vs HashTable

HashMap HashMap is the basic implementation of the map interface in Java. HashMap stores the data in key and value pairs. Keys are used to access the value of the element. It...

5 minutes read.

Java Implements Keyword

To understand about the keyword implements we need to learn about the concept of the interfaces and inheritance in java programming languages. So let us learn about the interface and...

3 minutes read.

Deadlock Prevention and avoidance in Java

This tutorial will discuss deadlock prevention and Avoidance in Java programming language. Introduction Multithreading in Java includes deadlock. We can multitask by running several threads concurrently in the multithreading environment. Deadlock occurs...

4 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Anonymous Function in Java

A function defined as being unbound from an identifier is called an anonymous function. Because they permit access to variables within the scope of the contained function, these are a...

4 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

How to run java program in ubuntu

To run the java programming in ubuntu, we need to follow several steps: Let's see the process. Step1: Install the Java compiler or JDK to the system. To run the java program, we...

3 minutes read.

Jagged Array in Java

Prerequisite We must first understand what Arrays are and Multi-dimensional Arrays are before we can learn about Jagged arrays. Java Arrays: A collection of data types that are similar is called an...

5 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Volatile keyword in Java

Multiple threads can change a variable's value by using the volatile keyword. Making classes thread-safe is another application for it. It indicates that using a method or an instance of...

3 minutes read.

Java Boolean compare() method

The compare() method of Java Boolean class compares the specified Boolean values and returns a positive 1 or negative 1 or zero integer value based on the result. Syntax public static int...

2 minutes read.

How to Convert String to float in Java

How to Convert String to Float in java It is used if you want to perform mathematical operations on the string that contains float number. You can convert String to float...

3 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.