Image

Java - Core Java - Collection Framework - Stack

Stack

  • It is a child class of Vector.
  • It is specially designed class for LIFO (Last In First Out).
  • When a stack is first created, it contains no element.
  • In this class the last element inserted is accessed first.
  • Class declaration
    Following is the declaration for java.util.Stack class
     public class Stack extends Vector
    
    Constructor
    public Stack(): Creates an empty Stack.
    
    Program
    import java.util.*;
    public class StackDemo1 {
        public static void main(String[] args) {
            Stack s=new Stack();
            s.push("A");
            s.push("B");
            s.push("C");
            System.out.println(s);
            System.out.println(s.search ("A"));
            System.out.println(s.search("2"));
            System.out.println(s.search("C"));
        }
    }
    O/P
    [A, B, C]
    3
    -1
    1