Stack in Java

  • A stack is a data structure that allows data to be inserted at one end called push operation and removed at another end called pop.
  • Stack class extends Vector class and implements standard Last in First out (LIFO) data structure.
  • Stack doesn’t require any fix dimension like String array and int array.
The following table demonstrates methods of the stack class

Method
Meaning
push()
Adds an item into the top of stack.
pop()
Removes the item from the stack and returns that item.
peek()
Returns the item from the top of the stack without removing it.
empty()
Returns true if the stack is empty.
search()
Returns the position of an object on the stack.

The following program shows a simple use of Stack.

Example:

/**
From SimpleStack.java
*/

import java.util.Stack;

/**
 *
 * @author JavaHotSpot
 */

public class SimpleStack
{
 public static void main(String args[])
 {
     Stack<String> st = new Stack<String>();
     st.push("Red");
     st.push("Green");
     st.push("Blue");
     st.push("Orange");
     st.push("Yellow");
     st.push("White");
     st.push("Black");
     System.out.println("Stack Elements are");
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
     System.out.println(st.pop());
 }
}

Output:
Stack Elements are
Black
White
Yellow
Orange
Blue
Green
Red

The following program shows of Stack with Iterator Interface.

Example:

/**
From StackWithIterator.java
*/
import java.util.Iterator;
import java.util.Stack;

/**
 *
 * @author JavaHotSpot
 */

public class StackWithIterator
{
  public static void main(String args[])
 {
     Stack<String> st = new Stack<String>();
     st.push("Red");
     st.push("Green");
     st.push("Blue");
     st.push("Orange");
     st.push("Yellow");
     st.push("White");
     st.push("Black");
     System.out.println("Stack Elements are");
     Iterator it = st.iterator();
     while(it.hasNext())
     {
         System.out.println(it.next());
     }
 }
}

Output:
Stack Elements are
Red
Green
Blue
Orange
Yellow
White