Gadgets

Showing posts with label Stack example. Show all posts
Showing posts with label Stack example. Show all posts

Thursday, 21 January 2016

Explain about Stack with an example

Stack is a child class of Vector. Stack is Last In First Out (LIFO).
Heterogeneous Objects are allowed.
Insertion order is preserved.
Duplicate Objects are allowed.
Null insertion is possible.

Constructor:
Stack s=new Stack();

Methods in Stack:
push() – To insert object into stack
pop() – To remove object
peek() – To return object without remove
boolean empty() – Return true if the stack is empty
int search() – Return offset, if the element is available otherwise return-1

import java.util.*;
public class StackDemo {
               public static void main(String[] arg) {                  
                               Stack s=new Stack();
                               s.push("a");
                               s.push("b");
                               s.push(null);//null insertion allowed
                               s.push("c");
                               s.push("a");//duplicates are allowed        
                               System.out.println(s); // [a, b, null, c, a]
                               s.pop();
                               System.out.println(s); //[a, b, null, c]
                               System.out.println(s.search("c")); // 1 (offset is 1)                            
               }
}