Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at

Tuesday, September 23, 2014

Stack class in Java : A complete overview


Stack is the subclass of Vector and implements Serializable, Clonable, Collection and List interface. Stack is the representation of LIFO data structure in Java.
  1. Underlined data structure is Stack (LIFO). 
  2. Heterogeneous data elements are allowed.  
  3. Null insertion is allowed. 
  4. Duplicates are allowed. 
  5. Insertion order is preserved.

Stack s=new Stack() //Creates an empty Stack

push(Object obj)
Insert an element on top of Stack
Remove and return an element from the top of Stack.
Return an element from the top of Stack.
search(Object o)
Return the offset if the passed object is found in Stack, -1 otherwise.


import java.util.*;
class StackDemo
public static void main(String[] args)
Stack s=new Stack();
for(int i=1;i<=5;i++)
System.out.println(s.peek()); //Returns the element at the top of stack
System.out.println(s.pop()); //Remove and returns the element from top of Stack

Output of the above program :


Diagrammatic representation of the above program :


If there are duplicate elements in the stack search(Object ob) method will return the offset of the element which is nearest to top of stack.

When to use Stack

Stack is useful when our requirement is to retrieve the element which came last or which added last. In other terms we can say that if we want to retrieve the latest inserted element then we should go for Stack.

No comments: