Way2Java

Java Stack Program

Java Stack Program

Summary: By the end of this tutorial "Java Stack Program", you will understand stack in Java. Very comfortable with the explaination and code examples.

Stack, in any language, stores elements in LIFO (Last-in First-out) order. As the name indicates, in LIFO, the last added element is retrieved first. It can be imagined like a stack of plates put on the top of the other. The plate added at the end is drawn first. In stack, elements cannot be added in the middle or removed. There can be only one point of entry and one point of exit.

Following is the class signature

public class Stack extends Vector

Java Stack is derived from Vector and again Vector is derived from List. List belongs to collections framework (JDK 1.2) and Stack and Vector belong to legacy classes (JDK 1.0 DS are known as legacy classes; they are Stack, Vector, Hashtable and Properties).

The Java designers extended List to Stack and Vector to give the features and advantages of collections (JDK 1.2 DS) to legacy classes (JDK 1.0 DS). It is a good designing principle. Now stack and vector can use all the methods of Collection and List interfaces.

The java.util.Stack comes with five operations represented by five methods.

  1. Object push(Object obj): An element obj is added the to the stack with push() method. Elements are added implicitly on the top of another. The method returns the element added.
  2. Object pop(): With this method, the elements can be retrieved from the Stack. The last one added (which lies on the top) is returned first. With pop(), the element comes out of the stack permanently. That is, it cannot be retrieved again.
  3. int search(Object obj): With this method, an element, obj, index number can be obtained. The counting starts from the top. The topmost element index number is 1. If the stack is empty, the method returns EmptyStackException.
  4. Object peek(): This method returns the element existing on the top. But element is not popped (removed) out. This method is best useful to know whether an element exists or not.
  5. boolean empty(): Returns true if no elements exist in the stack.
pop vs peek

For a beginner, these two methods are very confusing. Let us discuss again. The pop() method returns the element existing on the top of the stack. The element returned is deleted from the stack permanently. That is, the programmer cannot obtain it again.

The peek() method also returns the element but the element is not deleted from the stack. That is, calling peek() method five times, returns the same element 5 times. peek() method can be used to know which element is lying on the top of the stack or which element will returned when pop() is called. It can be used in regular programming like this.

       if(st.peek().equals("SNRao"))
       {
          System.out.println(st.pop());
       }

Limitations of Stack Usage

There are two limitations for stack usage.

  1. The programmer stores data in a DS with an intention to get the elements whenever he would like in the code. But with stack, the popped element is completely removed and cannot be obtained again. For this reason stack is not used much in general production software like health and banking etc, but used by system and tool developers.
  2. Another drawback is, the elements cannot be added or retrieved from the middle.

The Java Stack class comes with only one constructor.


Two programs are given on stack.
  1. The present one is general, storing any data type. The methods push, peek, pop, size etc. are used.
  2. The other one is generics stack storing similar or specific type of elements. Enhanced for loop (foreach) is used to iterate the elements.
Java Stack Program
import java.util.*;
public class GeneralStack
{
  public static void main(String args[])
  {
    Stack st = new Stack();
    System.out.println("Calling empty() before elements are added: " + st.empty());
    st.push(10);
    st.push(20);
    st.add(30);
    st.push("SNRao");
    st.add(20.5);
    st.add(new Date());
    st.push(true);
    st.push('A');
    st.push(50);
    System.out.println("Calling empty() after elements are added: " + st.empty());
    System.out.println("Elements in the stack: " + st);

    System.out.println("Index number of 50 counted from top: " + st.search(50));    
    System.out.println("Index number of SNRao from top: " + st.search("SNRao"));

    System.out.println("Element at the top: " + st.peek());
    System.out.println("No. of elements before pop called: " + st.size());
    System.out.println("Popped element: " + st.pop());
    System.out.println("No. of elements after pop is called: " + st.size());

    System.out.print("Technique of printing elements with empty():\n\t");
    while( ! st.empty() )     
    {		
      System.out.print(st.pop( ) + " ") ;
    }
    System.out.println("\nNo. of elements after while loop: " + st.size());
  }
}



Output of Java Stack Program

System.out.println(“Calling empty() before elements are added: ” + st.empty());

The empty() method returns true if no elements exist in the stack. As no elements are added still, the above statement returns true.

We know Stack is a legacy class and originally not part of collections framework. As Stack extends Vector and indirectly List also, Stack can make use of all the methods of Collection interface. add() is a method of Collection interface inherited by Stack. The original method of adding, defined in Stack class, is push(). Both methods are used in the program. This is how, the designers, gave compatibility to legacy classes with collection classes.

Following is the hierarchy of Stack.

Collection –> List –> Vector –> Stack

System.out.println(“Index number of A counted from top: ” + st.search(50));
System.out.println(“Index number of SNRao from top: ” + st.search(“SNRao”));

Using search method, the programmer can know at what position or index number, a particular element exist in the stack. The counting starts from the top element (added last). As 50 is added last, serach(50) returns 1. search("SNRao") returns 6. Observe the screenshot.

System.out.println(“Element at the top: ” + st.peek());

The peek() method returns the element at the top; that is 50. But the element is not removed from the stack. Observe the code, 50 is again printed with pop() method.

System.out.println(“No. of elements before pop called: ” + st.size());

The size() method returns the number of elements present in the stack. The same size() method when called after pop(), prints one less, 8 (original number is 9).

System.out.println(“Popped element: ” + st.pop());

The pop() method returns the top element. The element is permanently comes out and cannot be obtained again.

Observe when size() is called after while loop, it prints 0 as all the elements are removed from stack with iteration using pop() method; now stack is empty. Rewrite this Java stack program with different iterations to get command over the subject.

Real-time Examples of Stack Implementations

Following are a few examples of Stack in realtime.

With this knowledge of general Java stack program, now you can understand the second Java Stack program, Generics Stack.

Pass your comments to improve the quality of this tutorial" Java Stack Program".