Katerina Zamani

About Katerina Zamani

Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Java Queue Example

Java provides us Queue interface, where we can keep and handle elements before processing. Except the methods that Collection provides, it also supports some basic operations in order to simulate the classic queue structure. Each of these operations exists in two forms:

  • if a method fails, an exception is thrown. This form includes add(), remove() and element() methods.
  • if a method fails, a special value is returned (null or false). This form contains offer(), poll() and peek() operations.

It is worth to mention that FIFO (first-in-first-out) is the most common way to order the elements in the Queue. In this example we are going to show the operations in order to handle a queue.

1. Explanation of Queue operations

First of all, lets see analytically the basic operations that exist in two different forms.

1.1. Throws exception

  • add(E e): inserts the element e to the tail of the queue. If there is no space available because of capacity restrictions, IllegalStateException is thrown.
  • remove(): removes and returns the head (the first element) of the queue. If the queue is empty, NoSuchElementException is thrown.
  • element(): just returns the head of the queue, without removing it. If the queue is empty, again NoSuchElementException is thrown.

1.2. Returns special value

  • offer(E e): adds the element e to the tail of the queue. If the insertion is successful the method returns true, otherwise it returns false. Generally, if there are capacity bounds, it is preferred to use add method instead.
  • poll(): like remove() function, it retrieves and removes the head of the queue. The only difference from remove() is that poll() operation returns null when the queue is empty.
  • peek(): just like element() operation it retrieves and returns the head of the queue, without removing it. In this situation when the queue is empty, it returns null.

2. Example of Queue

Now, we are going to show in the code how to use the operations we explained above. So, create a new java file with the name QueueClass and paste the following code.


package com.javacodegeeks.core.queue;

import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;

public class QueueClass {

	public static void main(String[] args) {
		Queue myQueue = new LinkedList(); 

		// add elements in the queue using offer() - return true/false
		boolean flag = myQueue.offer("Wednesday");
		System.out.println("Wednesday inserted successfully? "+flag);
		// add more elements using add() - throws IllegalStateException
		try {
		} catch (IllegalStateException e) {
		System.out.println("Pick the head of the queue: " + myQueue.peek());
		String head = null;
		try {
			// remove head - remove()
			head = myQueue.remove();
			System.out.print("1) Push out " + head + " from the queue "); 
			System.out.println("and the new head is now: "+myQueue.element());
		} catch (NoSuchElementException e) {
		// remove the head - poll()
		head = myQueue.poll();
		System.out.print("2) Push out " + head + " from the queue");
		System.out.println("and the new head is now: "+myQueue.peek());
		// find out if the queue contains an object
		System.out.println("Does the queue contain 'Weekend'? " + myQueue.contains("Weekend"));
		System.out.println("Does the queue contain 'Monday'? " + myQueue.contains("Monday"));


As you can see in the code above, in order to create a queue we should assign LinkedList instance to the Queue object. In addition, you can notice how we call and use the functions we explained before. Also, it is worth to mention that you can use more methods that Queue inherits from Collection, such as contains() method.

You can see the output of the execution of the above code.


Wednesday inserted successfully? true
Pick the head of the queue: Monday
1) Push out Monday from the queue and the new head is now: Thusday
2) Push out Thusday from the queueand the new head is now: Wednesday
Does the queue contain 'Weekend'? true
Does the queue contain 'Monday'? false

Download the source file

This was a tutorial about Queue in Java. Download the source code of this example: QueueExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books