Java .peek()
In Java, the .peek() method retrieves the head element of a queue without removing it from the queue. If the queue has no elements, it returns null instead of throwing an exception. This makes it a safe way to check what element is next in line without modifying the queue structure.
Syntax
queueName.peek()
Return value:
Retrieves the head of the queue without removing it. Returns null if the queue is empty.
Example 1: Basic Usage of .peek()
This example demonstrates how .peek() is used to inspect the next element without removing it from the queue:
import java.util.Queue;import java.util.LinkedList;public class Main {public static void main(String[] args) {// Create a queue for customer serviceQueue<String> customerQueue = new LinkedList<>();// Add customers to the queuecustomerQueue.offer("Alice");customerQueue.offer("Bob");customerQueue.offer("Charlie");System.out.println("Queue: " + customerQueue);// Peek at the next customer without removing themString nextCustomer = customerQueue.peek();System.out.println("Next customer to be served: " + nextCustomer);// Queue remains unchanged after peekSystem.out.println("Queue after peek: " + customerQueue);System.out.println("Queue size: " + customerQueue.size());// Serve the customerString servedCustomer = customerQueue.poll();System.out.println("Served customer: " + servedCustomer);System.out.println("Updated queue: " + customerQueue);}}
The output of this code is:
Queue: [Alice, Bob, Charlie]Next customer to be served: AliceQueue after peek: [Alice, Bob, Charlie]Queue size: 3Served customer: AliceUpdated queue: [Bob, Charlie]
This example shows how .peek() provides read-only access to the head element, keeping the queue unchanged until an actual removal operation is performed.
Example 2: Handling Empty Queues with .peek()
This example shows how .peek() safely handles empty queues by returning null instead of throwing exceptions:
import java.util.Queue;import java.util.LinkedList;public class EmptyQueueHandling {public static void main(String[] args) {Queue<String> messageQueue = new LinkedList<>();// Peek at empty queueString result = messageQueue.peek();System.out.println("Peek on empty queue: " + result);System.out.println("Queue is empty: " + messageQueue.isEmpty());// Add some messagesmessageQueue.offer("Welcome message");messageQueue.offer("Alert notification");// Peek at non-empty queueString nextMessage = messageQueue.peek();System.out.println("Next message: " + nextMessage);// Process all messages while checking what's nextwhile (!messageQueue.isEmpty()) {String current = messageQueue.peek();System.out.println("About to process: " + current);String processed = messageQueue.poll();System.out.println("Processed: " + processed);// Check if there are more messagesString upcoming = messageQueue.peek();if (upcoming != null) {System.out.println("Next up: " + upcoming);} else {System.out.println("No more messages in queue");}System.out.println("---");}}}
The output of this code is:
Peek on empty queue: nullQueue is empty: trueNext message: Welcome messageAbout to process: Welcome messageProcessed: Welcome messageNext up: Alert notification---About to process: Alert notificationProcessed: Alert notificationNo more messages in queue---
This example demonstrates the safety of .peek() when dealing with potentially empty queues, making it ideal for defensive programming practices.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
- Beginner Friendly.17 hours