×

Stack in Java

Java provides a number of collection frameworks to store the collection of objects. Among the collection of data structures " Stack " is one of them. Stack is one of the linear data structures in Java. The main purpose of the " Stack " data structure is to store a collection of objects. It is based upon LIFO i.e., last in first out. It provides many operations like pop, push, etc…  It provides three more functions like search, empty, and peek.

  • To insert an element into the stack we use push operator.
  • To delete an element from the stack we use pop operator.
  • To search for an element in the stack we use search method.

Stack class

Stack class comes under the collection framework in Java. It is a subclass of "Vector". Stack is a specially designed class for LIFO (last in first out) order It extends the Vector class. It also implements interfaces like List etc... To use the Stack class, we need to import the " java.util " package.

Constructor of Stack

The stack class supports one default constructor Stack(). This constructor is used to create an empty stack.

public class Stack() extends Vector()

How to create a Stack?

The Stack class is created by first importing the package “ java.util”.

Stack s = new Stack ();

Or

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

In type, we write integer or string, etc…

StackConstructorExample.java

import java.util.Stack;
public class StackConstructorExample {  
    StackConstructorExample() {  
        System.out.println("Empty stack is created");  
    }  
    public static void main(String args[]) {  
        StackConstructorExample stack = new StackConstructorExample(); // calling constructor 
    }  
}

Output:

Java Stack

Operators in Stack class :

Whenever we use the word Stack, immediately two words come into our mind they are " push " and " pop ".

push() operator:

This operator is used to push or add an object into the stack. The element or object gets pushed on top of the stack. This operator returns the argument passed into it.

PushMethodExample.java

import java.util.*;  
public class PushExample {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>();  // empty stack is created
        stack.push(" Welcome ");  
        stack.push(" To ");  
        stack.push(" JavaTpoint ");  
        System.out.println(" Stack at beginning : " + stack);  
        // Push elements into the stack  
        stack.push("Hello");  
        stack.push("Programmers");  
        // Displaying the final Stack  
        System.out.println("Final Stack: " + stack);  
    }  
}

Output:

Java Stack

pop() operator :

This operator in Java is used to pop or remove an element from the stack. Any kind of parameters are not allowed in this operator. When we use the pop() method it returns the topmost element of the stack and removes it from the stack. This operator throws "EmptyStackException" when the Stack is empty.

PopExample.java

import java.util.*;  
public class PopExample {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>();  // empty stack is created
        stack.push(" Welcome ");  
        stack.push(" To ");  
        stack.push(" JavaTpoint ");  
        System.out.println(" Stack before poping: " + stack);  
        System.out.println(" Popped element: " + stack.pop());  // deleting topmost element (JavaTpoint)
        System.out.println(" Popped element: " + stack.pop());  // deleting next element (To)
        // Displaying the Stack after using the pop method 
        System.out.println(" Stack after pop operation " + stack);  
    }  
}

Output:

Java Stack

PopExample1.java

import java.util.*;  
public class PopExample1 {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>();  //empty stack is created
        stack.push(" Welcome ");  
        stack.push(" To ");  
        stack.push(" JavaTpoint ");  
        System.out.println(" Stack before poping: " + stack);  
        System.out.println(" Popped element: " + stack.pop());  // deleting top most element (JavaTpoint)
        System.out.println(" Popped element: " + stack.pop());  // deleting next element (To)
        System.out.println(" popped element: " + stack.pop()); // delecting last element (Welcome)
        System.out.println(" popped element: " + stack.pop()); // Empty Stack Exception
         }  
}

Output :

Java Stack

The above program throws an error. There we are trying to delete an element from an empty stack, so it throws the "EmptyStackException" exception.

Methods in the Stack class :

The well-known methods of the Stack class are “ peek ”, “ search ” and “ empty ”.

peek() method in the Stack class :

To use the peek() method we need to import the " java.util.Stack " package. This method returns the topmost element of the stack. It only retrieves the topmost element but does not delete the element from the stack, this is the difference between the pop() operator and peek() method.

Syntax :

Stack name.peek();

PeekMethodExample.java

import java.util.Stack;  
public class PeekMethodExample {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>(); // empty stack is created
        stack.push(" Welcome ");  // adding elements to the stack
        stack.push(" To ");  
        stack.push(" JavaTpoint ");  
        System.out.println(" Stack before using peek: " + stack);  
        System.out.println(" Displaying the top element using peek method : " + stack.peek());  // using peek() method
        System.out.println(" Stack after using peek: " + stack);  
    }  
}

Output :

Java Stack

PeekMethodExample1.java

import java.util.Stack;  
public class PeekMethodExample1 {  
    public static void main(String args[]) {  
        Stack<String> stack = new Stack<String>(); // empty stack is created
        System.out.println(" Stack before using peek: " + stack);  // displaying empty stack
        System.out.println(" Displaying the top element using peek method : " + stack.peek());  // using peek() method
         }  
}

Output:

Java Stack

search() method in the Stack class :

For searching any element in the stack search() method is used. It returns the  distance of the element from the top. Here stack index starts from 1, not 0. If a stack contains similar elements, then it returns the index of the nearest element to the top. If the element is not present in the stack, then it returns "-1".

SearchMethodExample.java

import java.util.*;  
public class SearchMethodExample {  
    public static void main(String[] args) {  
        Stack<String> stack = new Stack<String>();  // creating empty stack
        stack.push(" Hello ");  // adding elements to the stack
        stack.push(" programmers");  
        stack.push(" Welcome ");  
        stack.push(" To ");  
        stack.push(" JavaTpoint ");  
        System.out.println("The stack is: " + stack);  // displaying the stack
        System.out.println(" Hello is present at? " + stack.search(" Hello "));  // searching the element
        System.out.println(" To is present at? " + stack.search(" To ")); 
  System.out.println(" Java is present at? " + stack.search("Java"));  // searching for an element which is not present in the stack
 }  
}

Output :

Java Stack

empty() method in Stack class :

An empty () method in Java is used to check whether the stack is empty or not. It is like a Boolean type. If the stack is empty, It returns true, or else it returns false. Arguments are not allowed in this method.

EmptyMethodExample.java

import java.util.*;  
public class EmptyMethodExample {  
    public static void main(String[] args) {  
        Stack<String> stack = new Stack<String>();  // empty stack is created
        System.out.println("Is the stack empty? " + stack.empty());  // returns true
    }  
}

Output :

Java Stack

Related Topics

Contextual keywords in Java

Contextual keywords were earlier known as restricted identifiers and restricted keywords. Context keywords are chosen based on their expected placement in the syntactic grammar. These are the keywords in the code...

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.

Why String in Immutable in Java?

Why String in Immutable in Java Immutable means unchangeable or unmodifiable.  Strings in Java are immutable, it means once a string is created, it cannot be modified or changed. Any change...

2 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

Java Null Keyword

Null is a term that is only used for literal values in Java. Although it appears to be a term, it is a literal opposite of true and false. Java's...

3 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.

ArrayList Program in Java

ArrayList Program in Java: In Java, ArrayList is a class that belongs to java.util package. It is the dynamic list that grows or shrinks at run-time as per the requirements....

4 minutes 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 get the current date and time in Java

Introduction: In this article, we are going to discover many processes for Getting the existing-day Date and Time in Java. Most programs require timestamping events or showing date/times, among many...

3 minutes read.

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types....

6 minutes read.