×

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

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 minutes read.

Java Math multiplyFull() Method

The multiplyFull() method of Math class returns the exact product of the arguments. Syntax: public static long multiplyFull (int x, int y) Parameters: The parameters ‘x’ and ‘y’ represent the first value and second...

1 minute read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

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

Shopping Bill in Java

Java Shopping Bill Here in this program, we are about to create a JAVA class called Products which will have some properties or attributes like prod_name (Product Name ), qty (quantity),...

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

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.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

How to write basic Java Programs

Java Basic Programs In this section, we will learn how to write basic Java programs. But first we need to take care of the following requirement list. To execute a Java program,...

4 minutes read.

JDBC Architecture

JDBC: JDBC stands for Java Database Connectivity. Sun Microsystems has a specification called JDBC. JDBC is a Java API (Application Programming Interface) that enables users to interact or communicate with...

4 minutes read.

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Java Linters

When it comes to programming, everyone makes mistakes. Errors are bad for developers since they are difficult to handle. But handling as many as possible errors will bring out the...

6 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.