Java .element()
Anonymous contributor
Published Aug 7, 2025
Contribute to Docs
In Java, the .element() method of the Queue interface retrieves, but does not remove, the head of the queue. Unlike .peek(), which returns null if the queue is empty, .element() throws a NoSuchElementException in such cases. This method provides a way to inspect the next element to be removed without modifying the queue’s structure.
Syntax
queueName.element()
Parameters:
The .element() method does not take any parameters.
Return value:
- Returns the head element of the queue.
- Throws
NoSuchElementExceptionif the queue is empty.
Example
This example demonstrates the .element() method with a LinkedList implementation of Queue:
import java.util.LinkedList;import java.util.Queue;import java.util.NoSuchElementException;public class Main {public static void main(String[] args) {Queue<String> animals = new LinkedList<String>();// Add elements to the queueanimals.offer("Dog");animals.offer("Cat");animals.offer("Bird");// Use .element() to peek at the head without removing itSystem.out.println("Head element: " + animals.element());System.out.println("Queue after element(): " + animals);// Remove elements and check headanimals.poll();System.out.println("Head after poll: " + animals.element());// Clear the queueanimals.clear();// Attempting to use .element() on empty queue throws exceptiontry {animals.element();} catch (NoSuchElementException e) {System.out.println("Exception: Queue is empty!");}}}
Here is the output:
Head element: DogQueue after element(): [Dog, Cat, Bird]Head after poll: CatException: Queue is empty!
All contributors
- Anonymous contributor
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