Stack Java example

Stack Java example

public class Stack extends Vector

Stack represents last-in-first-out (LIFO) of objects. This extends Vector class includes five operations which allow vector also treated as stack. Its push operation push object in stack, pop operations remove the object from stack and peek operation returns top value on stack. Its method empty is to test if stack is empty or not and method search returns how far the object in the stack from top.
Deque class is preferable compare to stack because it has consistent and complete set of LIFO operations has provided.

Example Stack test java class:

package com.javahonk.action;

import java.util.Stack;

public class StackTest {

    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<Integer>();

        for (int i = 1; i <= 5; i++) {
        //Print top value on stack 
        System.out.println("Top value on stack: "+stack.peek());
        //Search element position on stack
        int positionOfElement =;
        System.out.println("\nElement postion 4 from bottom: "
        //Remove single element from stack
        System.out.println("\nAfter remove one value from stack:");
        //Print value after removes
        for (Integer integer : stack) {
        //Remove all element from stack
        while (!stack.empty()) {
        // Print value
            System.out.println("\nStack is empty");




Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *