Friday, 20 February 2015

Using a Stack in Java

Someone asked me to help him with a basic code of using a stack and here it is: Just creating a stack and adding 3 string objects to it using push then playing around with the methods iimplemented in a stack object.


public class StackExample {
   
    public static void main(String[] args) {
       
        Stack st = new Stack();
        st.push("Onty");
        st.push("Bagwasi");
        st.push("Programming");
       
        //prints the first element in the stack - Onty
        System.out.println(st.firstElement());
       
        //prints the element at index 0 - Onty
        System.out.println(st.get(0));
       
        //prints the index of Bagwasi - 1
        System.out.println(st.indexOf("Bagwasi"));
       
        //prints the last element in the stack
        System.out.println(st.lastElement());
       
        //this just checks what the last element is and prints it
        System.out.println(st.peek());
       
        //pop gets the last item in the stack and removes it from the stack
        st.pop();
       
        //now if u peek, the last item on the stack has changed
        System.out.println(st.peek());
    }
   
}