Java Stack peek() Method Example

This example demonstrates the usage of Stack peek() method with an example.
Stack peek() method looks at the object at the top of this stack without removing it from the stack.

Java Stack peek() Method Example

Let's demonstrate the usage of the peek() method with an example:
package com.javaguides.collections.stackexamples;

import java.util.Stack;

public class StackMethodExample {

    public static void main(String[] args) {
        peekMethod();
    }

    private static void peekMethod() {
        // creating stack
        Stack < String > stack = new Stack < > ();

        // populating stack
        stack.push("Java");
        stack.push("JEE");
        stack.push("C");
        stack.push("C++");
        stack.push("Spring");
        stack.push("Hibernate");

        // checking the top object
        System.out.println("Top object is: " + stack.peek());
    }
}
Output:
Top object is: Hibernate

Reference

Comments