Java-Stack with example

Stack is a subclass of Vector that implements a standard last-in, first-out stack.
Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own.

This diagram shows the hierarchy of Stack class:


Method Summary

Modifier and Type Method and Description
boolean empty()
Tests if this stack is empty.
Object peek()
Looks at the object at the top of this stack without removing it from the stack.
Object pop()
Removes the object at the top of this stack and returns that object as the value of this function.
Object push(E item)
Pushes an item onto the top of this stack.
int search(Object o)

Returns the 1-based position where an object is on this stack.


Example
import java.util.EmptyStackException;
import java.util.Stack;



//Java code for stack implementation 

public class KnowledgeFactoryStackDemo {
// Displaying element on the top of the stack
static void showpeek(Stack<Integer> st) {
Integer a = st.peek();
System.out.println("peek: " + a);
}



// Searching element in the stack

static void search(Stack<Integer> st, int a) {
System.out.println("search: " + st.search(a));
}



// Searching isEmpty stack

static void isEmpty(Stack<Integer> st) {
System.out.println("isEmpty: " + st.isEmpty());
}



// Pushing element on the top of the stack

static void showpush(Stack<Integer> st, int a) {
st.push(a);
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}



// Popping element from the top of the stack

static void showpop(Stack<Integer> st) {
System.out.print("pop -> ");
Integer a = st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}



public static void main(String args[]) {

Stack<Integer> st = new Stack<Integer>();
System.out.println("stack: " + st);
showpush(st, 33);
showpush(st, 88);
showpush(st, 199);
showpeek(st);
search(st, 88);
search(st, 55);
isEmpty(st);
showpop(st);
showpop(st);
showpop(st);
isEmpty(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}


Output:

stack: []
push(33)
stack: [33]
push(88)
stack: [33, 88]
push(199)
stack: [33, 88, 199]
peek: 199
search: 2
search: -1
isEmpty: false
pop -> 199
stack: [33, 88]
pop -> 88
stack: [33]
pop -> 33
stack: []
isEmpty: true
pop -> empty stack


This article is contributed by Sibin. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above

Comments

  1. Genuine and Free jobs!
    Don't miss any job opportunities!
    Improve your life, only one step!

    More Java jobs info, Please join the Java Jobs group:
    https://chat.whatsapp.com/HLFm93tkHQR4zu8hafpqSl

    ReplyDelete

Post a Comment