Stack Class Java

Stack Class Java with Programming Example

Stack Class JavaIn this chapter you will learn:

  1. What is stack class in java?
  2. How to initialize stack?
  3. Methods of stack class
  4. Programming Example
 What is stack class in Java?

Stack is based on Last-in-First-Out (LIFO) module. It is a subclass of vector class. In the stack the item which is added first in the list can be accessed last and the item which is added last can be accessed first.
For example:

  • Wearing bangles.
  • Stack of CD.
  • Stack of Book etc

How to declare stack?

 public class Stack
   extends Vector

Constructors and methods

It includes all the methods of vector class and it also defines several other methods.

 

Programming Example

import java.util.*;
public class Stack_Example
{
  public static void main(String[] args)
  {
    //Create Empty Stack
    Stack stk=new Stack();
    System.out.println("Items on Stack : " + stk);
    
    //Adding items to Stack
    stk.push("A");
    stk.push("B");
    stk.push("C");
    try
    {
    //Retrieving Stack
    System.out.println("Removing Top Items : " + stk.pop());
    System.out.println("Now items are : " + stk);
    
    System.out.println("Removing Top Items : " + stk.pop());
    System.out.println("Now items are : " + stk);
    
    System.out.println("Removing Top Items : " + stk.pop());
    System.out.println("Now items are : " + stk);
    
    System.out.println("Removing Top Items : " + stk.pop());
    System.out.println("Now items are : " + stk);
    }
    catch(EmptyStackException e)
    {
      System.out.println("Stack Empty");
    }
    
  }
}



Output

D:\JavaProgram>javac Stack_Example.java

D:\JavaProgram>java Stack_Example
Items on Stack : []
Removing Top Items : C
Now items are : [A, B]
Removing Top Items : B
Now items are : [A]
Removing Top Items : A
Now items are : []
Stack Empty
_

Explanation

In the above example we push() method is used for adding items on the stack and pop()method is used for removing items from the top.

Summary

In this chapter you have learned stack class in java collection and their methods with complete programming example. In the next chapter you will learn Queue Interface in Java.


Leave a Reply

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