×

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

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Java String concat() method:

Java String concat() method is used to add the given String to the end of the current String. Syntax: public String concat(String str) Parameter: Str: String to be concatenated at the end of current...

1 minute read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Package naming convention in Java

It is conceivable that many programmers will use the same name for various types, given that Java programmers from all over the world create classes and interfaces. For illustration, suppose...

4 minutes read.

Java Integer highestOneBit()

The highestOneBit() method of Java Integer class returns an int value with at most a single one-bit, in the position of the highest-order one-bit in the specified int value.  Syntax public static...

1 minute read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.

Reentrant Lock in Java

The Lock interface is implemented by the ReentrantLock class, which also provides methods for synchronising access to shared resources. The code that controls the resource has calls to the lock...

4 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

String to JSON in Java

Nowadays, receiving data in JSON String format rather than XML is quite frequent. Java does not transform JSON String to JSON Object when dealing with JSON String. However, using the...

3 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

Java Hello World

Let’s start by writing a simple program that prints “Hello World” to the output window. Write the program into any text editor or IDE (Eclipse, Netbeans, etc.) and save the file with the...

2 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Buffer Reader

When a variable cannot change its value during run time is called a Static way of programming. In this programming, a variable is directly assigned to a value. Program: Import java.io.*; class  A {  ...

4 minutes read.