The “stack.peek()” is a well-known stack function in Java that retrieves the reference of the top-most element. It retrieves “java.util.EmptyStackException” if the targeted stack is empty.
A stack in Java is a linear data structure that follows the Last In, First Out (LIFO) principle. Therefore, it allows us to insert, delete, or retrieve elements from the top of the stack. The following image depicts how the peek() method works on a stack:
This post will illustrate the use of the “Stack.peek” method in Java with appropriate examples:
How to Use Stack.peek() Method in Java
To use the stack.peek() method in Java, call it on the selected stack using the dot syntax, as follows:
stackName.peek();
- Replace the “stackName” with the name of the targeted stack whose first element you want to fetch.
- The peek() method doesn’t accept any parameter(s).
Note: You can implement the peek() method on other well-known data structures as well, such as the LinkedList, Queue, Array, etc.
Let’s implement this method practically and see how it works in Java.
Example 1: How to Use peek() Method on a Stack
Java offers various methods to manipulate the stack’s data, such as “push()”, “pop()”, “isEmpty()”, and many others. These methods are used to perform various tasks like adding new elements to a stack, removing elements from a stack, checking whether a stack is empty, etc. In the below code, first, we create an empty stack and then we use the push() method to add elements to it:
import java.util.Stack;
public class StackPeekMethod {
public static void main(String args[]) {
Stack<String> givenStack = new Stack<String>();
givenStack.push("JavaBeat");
givenStack.push("javabeat.net");
givenStack.push("Welcome to javabeat.net");
System.out.println("The Original Stack is: " + givenStack);
System.out.println("The Topmost Element of the stack is: " + givenStack.peek());
}
}
We wrap the peek() method within the println() method to get and print the topmost element of the selected stack “givenStack”:
Example 2: How to Fix “java.util.EmptyStackException” in Java
If you try to execute peek() on an empty stack, you will face the “java.util.EmptyStackException”:
To avoid this exception, it is recommended to use the isEmpty() method with the if-else statement, as demonstrated in the following example:
import java.util.Stack;
public class StackPeekMethod {
public static void main(String args[]) {
Stack<String> peekExample = new Stack<String>();
if (peekExample.isEmpty())
{
System.out.println("The Selected Stack is Empty");
}
else{
System.out.println("The Topmost Element of the stack is: " + peekExample.peek());
}
}
}
In this example, we use the isEmpty() method within the if statement to check if a stack contains some elements or if it is empty. The if block will execute when the selected stack is empty and it will print a message accordingly. However, if the given stack contains some elements then the else block will execute which will retrieve the topmost element of the stack:
Example 3: How to Use peek() Method on a LinkedList
As discussed earlier, you can use the peek method on some other well-known data structures like a LinkedList, to get the top element of the selected data structure. For example, in the below code, we apply the peek() method on an “exampleLinkedList” to retrieve its top element:
import java.util.LinkedList;
public class StackPeekMethod {
public static void main(String args[]) {
LinkedList<String> listExample = new LinkedList<String>();
listExample.add("JavaBeat");
listExample.add("javabeat.net");
listExample.add("Welcome to javabeat.net");
System.out.println("The Original Stack is: " + listExample);
System.out.println("The Topmost Element of the list is: " + listExample.peek());
}
}
In this code, we declare a string-type LinkedList and add multiple elements to it using the add() method. Finally, we use the peek() method to get the top element of the selected LinkedList:
Java Stack pop() Vs peek() – What’s the Difference
The difference between the pop() and peek() methods is that the pop() method retrieves and removes the top element of the stack. However, the peek() method retrieves the top element without removing it. The below code snippet exemplifies the difference between the stated methods practically:
import java.util.Stack;
public class StackPeekMethod {
public static void main(String args[]) {
Stack<String> givenStack = new Stack<String>();
givenStack.push("Java");
givenStack.push("Beat");
givenStack.push(".net");
System.out.println("The Original Stack is: " + givenStack);
System.out.println("\nReturning Value of peek: " + givenStack.peek());
System.out.println("Stack After Implementing the peek Method: " + givenStack);
System.out.println("\nReturning Value of peek: " + givenStack.pop());
System.out.println("Stack After Implementing the pop Method: " + givenStack);
}
}
The output shows a side-by-side comparison of the original stack, and the stack after implementing the pop() and peek() methods:
That’s all about the use of the “Stack.peek()” method in Java.
Related Guides: Visit the linked guide to learn how the Stream peek() Method works in Java.
Bottom Line
To use the “Stack.peek()” method in Java, simply call it on the targeted stack via the dot syntax, i.e., “stackName.peek()”. The peek() method retrieves the top(last inserted) element of the selected stack. However, it throws an error “EmptyStackException”, if the selected stack doesn’t contain any element. This write-up has walked you through different use cases of the peek() method with respect to the stack and some other well-known data structures, such as LinkedList.