×

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

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Transient

Java Transient In Java, Serialization is used to convert an object into a stream of the byte. The byte stream consists of the data of the instance as well as the...

3 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 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.

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 try catch

Java try catch There can be statements that can cause exceptions, and the exception leads to abnormal termination of the program. To avoid that abnormal termination, those statements that look potent...

4 minutes read.

Java Worker Class

What is a Worker? A service which executes Work - flow and Activities is referred to as a Worker. On user-controlled hosts, workers are defined and put into action. The Worker...

3 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.

Java Polymorphism

The process of representing one form in multiple forms is known as Polymorphism. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means...

5 minutes read.

Statements in java

What is Statement in java: A statement in java is an instruction that explains what will happen based on the condition. Types of java statements: There are different statements in java Expression statementDeclaration statementControl...

2 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Java FileNotFoundException

FileNotFoundException is another exception class accessible in the java.io bundle. The exemption happens when we attempt to get to that document which isn't accessible in the framework. It is a checked...

5 minutes read.

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

RMI program in Java

Remote Method Invocation is what it stands for. An object can call the method of another object in a different space address using the RMI API, which may be on the...

3 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.