Java Stack – Stack In Java

Filed Under: Java

Java Stack is a legacy Collection class. It extends Vector class with five operations to support LIFO (Last In First Out). It is available in Collection API since Java 1.0.

As Vector implements List, Stack class is also a List implementation class but does NOT support all operations of Vector or List. As Stack supports LIFO, it is also known as LIFO Lists.

Java Stack

In this post we will discuss following concepts about Stack in java.

  1. Java Stack
  2. Java Stack Class Diagram
  3. Java Stack Methods
  4. Java Stack Basic Example
  5. How Stack’s push() and pop() works Internally?
  6. Java Array to Stack Example
  7. Java List to Stack Example
  8. Java Stack to List Example

Java Stack

Java Stack is LIFO object. It extends Vector class but supports only five operations. Java Stack class has only one constructor which is empty or default constructor. So, when we create a Stack, initially it contains no items that mean Stack is empty.

Stack internally has a pointer: TOP, which refers to the top of the Stack element. If Stack is empty, TOP refers to the before first element location. If Stack is not empty, TOP refers to the top element.

Java Stack Class Diagram

Java Stack extends Vector class directly and implements RandomAccess, List, Collection etc. interface indirectly. It is a LIFO list.

java stack

Java Stack Methods

Java Stack extends Vector class with the following five operations only.

  1. boolean empty(): Tests if this stack is empty.
  2. E peek(): Looks at the object at the top of this stack without removing it from the stack.
  3. E pop() : Removes the object at the top of this stack and returns that object as the value of this function.
  4. E push(E item) : Pushes an item onto the top of this stack.
  5. int search(Object o) : Returns the 1-based position where an object is on this stack.

We will discuss these operations in-depth in the coming sections with some useful examples.

Java Stack Example

It’s time to develop basic Java Stack example to explore it’s operations.


import java.util.Stack;

public class StackBasicExample {
    public static void main(String a[]){
        Stack<Integer> stack = new Stack<>();
        System.out.println("Empty stack : "  + stack);
        System.out.println("Empty stack : "  + stack.isEmpty());
        // Exception in thread "main" java.util.EmptyStackException
        // System.out.println("Empty stack : Pop Operation : "  + stack.pop());
        stack.push(1001);
        stack.push(1002);
        stack.push(1003);
        stack.push(1004);
        System.out.println("Non-Empty stack : "  + stack);
        System.out.println("Non-Empty stack: Pop Operation : "  + stack.pop());
        System.out.println("Non-Empty stack : After Pop Operation : "  + stack);
        System.out.println("Non-Empty stack : search() Operation : "  + stack.search(1002));
        System.out.println("Non-Empty stack : "  + stack.isEmpty());
    }
}

Output:


Empty stack : []
Empty stack : true
Non-Empty stack : [1001, 1002, 1003, 1004]
Non-Empty stack: Pop Operation : 1004
Non-Empty stack : After Pop Operation : [1001, 1002, 1003]
Non-Empty stack : search() Operation : 2
Non-Empty stack : false

How Stack’s push() and pop() operations works Internally?

As we know Stack’s push() and pop() are most frequently used Stack operations. The push() operation is used to insert an element into a Stack at the top. The pop() operation is used to remove the top element from a Stack.

Stack data structure has one internal property: top to refer top element of that stack. If Stack is empty, this top refers to the before first element as shown below:

stack in java

As shown in the below diagram, Stack’s Push operation always inserts new element at the top of the Stack.
java stack example

As shown in the below diagram, Stack’s Pop operation always removes an element from the top of the Stack.
stack java program

Stack’s isEmpty() operation returns True if there are no elements, otherwise, it returns False.

Java Array to Stack Example

Let us explore on “How to create a Stack object with a given Int array” here.


import java.util.Stack;

public class ArrayToStackExample {
    public static void main(String a[]){
        Integer[] intArr = { 1001,1002,1003,1004};
        Stack<Integer> stack = new Stack<>();
        for(Integer i : intArr){
            stack.push(i);
        }
        System.out.println("Non-Empty stack : "  + stack);
    }
}

Output:-


Non-Empty stack : [1001, 1002, 1003, 1004]

Java List to Stack Example

Let us explore on “How to create a Stack object with a given List of Integers” here.


import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class ListToStackExample {
    public static void main(String a[]){
        Stack<Integer> stack = new Stack<>();
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println("Non-Empty stack addAll Operation : "  + stack.addAll(list));
        System.out.println("Non-Empty stack : "  + stack);
    }
}

Output:-


Non-Empty stack : true
Non-Empty stack : [1, 2, 3]

Java Stack to List Example

Let us explore on “How to create a List object with a Stack of Integers” here.


import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class StackBasicExample {
    public static void main(String a[]){
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        List<Integer> list = new ArrayList<>();
        list.addAll(stack);
        System.out.println("Non-Empty stack : "  + stack);
        System.out.println("Non-Empty List : "  + list);
    }
}

Output:-


Non-Empty stack : [1, 2, 3]
Non-Empty List : [1, 2, 3]

That’s all of a quick roundup on Stack in Java. I hope these Java Stack basics and examples will help you in getting started with Stack programming.

Thank you for reading my tutorials. Please drop me a comment if you like my tutorials or have any issues or suggestions or any type errors.

Reference: API Doc

Comments

  1. ANSH says:

    Stack’s isEmpty() returns true if there is no element in the Stack. Below line seems to be indicating the opposite.

    “When Stack is with no elements, Stack’s isEmpty() operation returns false and in all cases it returns true.”

    1. Pankaj says:

      Yes you are right, I have changed the text to make it more clear and corrected it.

  2. AATIF says:

    I copied the code but but in my system there is no such class to import i.e. “import java.util.Stack;” ???!!!

    1. denny says:

      that could be you jdk not include stack library you can try to update your jdk

  3. ifat ijaz says:

    very nice programming we learn lot of knowledge from it.

  4. Mysarra Azmi says:

    Thanks a lot … This helps so much T.T

  5. Omairi says:

    can you help me to answer this :

    Write a main function that creates two stacks of Integer objects and a queue of Integer objects. Store the numbers −1, 15, 23, 44, 4, and 99 in the first stack. The top of the stack should store 99.

    2. Write a loop to get each number from the first stack and store it in the second stack and in the queue.

    3. Write a second loop to remove a value from the second stack and from the queue and display each pair of values on a separate output line. Continue until the data structures are empty. Show the output.

  6. Kishore Babu Posa says:

    Hi Anna Could you please share me some posts on ‘How to deal Groovy with Gradle in Eclipse IDE?’

  7. Banyuken says:

    Also, you have this text duplicated, it’s the other way around in the second case:

    Java List to Stack Example

    Let us explore on “How to create a Stack object with a given List of Integers” here.

    1. Rambabu says:

      Thanks for finding typo error. Fixed that

  8. Banyuken says:

    “When Stack is with no elements, Stack’s empty() operation returns false and in all cases it returns true.”

    This doesn’t make a lot of sense to me.

    1. Tol says:

      Indeed, looks like entirely opposite thing)

      1. Rambabu says:

        Hi Im bit confused about your comment. Please make it clear.
        Ram

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages