Stack

Stack is the subclass of Vector. The manner on what basis stack works is last in first out order(LIFO).

Constructor:

Stack s=new Stack(); it will create empty stack object with default size. Stack s=new Stack(int size); it will create empty stack object with specified size.

Commonly used methods of Stack:


public void push(Object element):

This method inserts an element at the front the stack.

public Object pop():

This method removes and returns the first element (top) from the stack.

public Object peek():

This method returns the first element (top) from stack without removing the element.

public boolean empty():

This method returns true when the Stack does not contain any elements.

public int search(Object o):

This method returns the offset value if element present in the stack otherwise it returns -1.

public int search(Object o):

This method returns the offset value if element present in the stack otherwise it returns -1.

import java.util.*;
class Test244
{
public static void main(String[] args)
{
Stack s1=new Stack();
s1.push("A");
s1.push("B");
s1.push("C");
System.out.println(s1.search("A"));//3
System.out.println(s1);//[A,B,C]
s1.pop();
System.out.println(s1);//[A,B]
System.out.println(s1.search("A"));//2
}
}
Footer with Map