Stack class in java

 

Basically Stack represents last-in-first-out (LIFO) ordering of objects. In Java Stack extends Vector and defines its own five methods along with default methods which allow a vector to be treated as a stack and those methods are
Stack class in java

push()
- Pushes the element or object into the stack and it returns the same element. 

pop()
- Removes the first element from the stack and it returns the same element. 
empty()

- Checks whether the stack is empty or not. Returns true if stack is empty else false.

peek()
- Similar to pop(), return first element from the stack but it won't remove the element. 

search()
- Searches for the element from the stack and returns the offset of the element if found else returns -1. 

Lets see simple example in java how to use Stack class.


import java.util.Stack;

public class StackTest {

 public static void main(String[] args) {
  
  Stack<Integer> stack = new Stack<Integer>();
  
  int stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //PUSH
  stack.push(11);
  stack.push(21);
  stack.push(31);
  stack.push(41);
  stack.push(51);
  
  stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //STACK
  System.out.println("STACK      : "+stack);
  
  //PEEK
  System.out.println("PEEK       : "+stack.peek());
  
  //POP
  System.out.println("POP        : "+stack.pop());
  
  
  stkSize = stack.size();
  System.out.println("STACK SIZE : "+stkSize);
  
  //PEEK
  System.out.println("PEEK       : "+stack.peek());
  
  //EMPTY
  System.out.println("EMPTY      : "+stack.empty());
  
  //SEARCH
  System.out.println("SEARCH     : "+stack.search(21));
  
  //SEARCH
  System.out.println("SEARCH     : "+stack.search(700));
 } 
}


OUTPUT:


STACK SIZE  : 0
STACK SIZE  : 5
STACK         : [11, 21, 31, 41, 51]
PEEK           : 51
POP            : 51
STACK SIZE : 4
PEEK          : 41
EMPTY        : false
SEARCH      : 3
SEARCH      : -1



No comments:
Write comments