Home  >  Core Java

Example of Stack in Java

By Arvind Rai, June 09, 2013
java.util.Stack behaves as Stack i.e. first in last out. push() and pop() methods are there in Stack. push() method pushes the element at the top of element. pop() method removes the element from the top. Find the example.

StackDemo.java
package com.concretepage.util;
import java.util.Stack;
public class StackDemo {
    public static void main(String[] args) {
        Stack st = new Stack();
        st.add("A");
        st.add("B");
        st.add("C");
        for(String s : st){
            System.out.println(s);
        }
        //returns current capacity of Stack
        System.out.println(st.capacity());
        //returns true if empty
        System.out.println(st.empty());
        //returns first element
        System.out.println(st.firstElement());
        //returns last element
        System.out.println(st.lastElement());
        //gets the top element but does not remove
        System.out.println(st.peek());
        //pushes the element at the top of element
        System.out.println(st.push("D"));
        //removes the element from the top
        System.out.println(st.pop());
        
    }
}
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us