Provide Best Programming Tutorials

Stack In Java

Introduction

The 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. The stack includes all the methods defined by Vector and adds several of its own.

Stack( )

Apart from the methods inherited from its parent class Vector, Stack defines the following methods −

Sr.No. Method & Description
1 boolean empty()

Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.

2 Object peek( )

Returns the element on the top of the stack, but does not remove it.

3 Object pop( )

Returns the element on the top of the stack, removing it in the process.

4 Object push(Object element)

Pushes the element onto the stack. The element is also returned.

5 int search(Object element)

Searches for an element in the stack. If found, its offset from the top of the stack is returned. Otherwise, -1 is returned.

Example:

import java.util.Stack;

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

        stack.push("Andrew");
        stack.push("Tracy");
        stack.push("Kobe");
        stack.push("James");

        System.out.println(stack);

        // Looks at the object at the top of this stack without removing it from the stack.
        stack.peek();

        //Removes the object at the top of this stack and returns that object as the value of this function.
        stack.pop();

        //Returns the 1-based position where an object is on this stack.
        System.out.println(stack.search("Tracy"));
        System.out.println(stack);

    }
}

output

[Andrew, Tracy, Kobe, James]
2
[Andrew, Tracy, Kobe]

 

Leave a Reply

Close Menu