Skip to content

Java stack class

  • by

Stack Class :

  • It is child class of vector
  • It is a specially designed class for last in first out order(LIFO)

CONSTRUCTOR

Stack s = new stack();

Operations:

  • push(Object o)
  • pop() offset
  • peek()
java stack example


 
 
 
 
 
s.search(A) //3
s.search(Z) ;//-1

Methods:

  • Object push(Object obj):-For inserting an object to the stack.
  • Object pop():-To removes and return top of the stack.
  • Object peek():-To returns the top of the stack without removal of the object.
  • int search(Object obj):-If the specified object is available it returns its offset from the top of the stack. If the object is not available then it returns -1.
  • Object top():- For inserting an object to the stack.

Example of stack:

import java.util.Stack;

public class StackDemo{
	
	public static void main(String args[]){
		
		Stack s = new Stack();
		s.push("A");
		s.push("B");
		s.push("C");
		System.out.println(s);//[A B C] INSERTION ORDER MUST BE PRESERVED
		System.out.println(s.search("Z"));//[-1]
	}
}

Output :

[A, B, C]
-1

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading