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.

QueueClass.java:

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
		myQueue.offer("Monday");
		myQueue.offer("Thusday");
		boolean flag = myQueue.offer("Wednesday");
		
		System.out.println("Wednesday inserted successfully? "+flag);
		
		// add more elements using add() - throws IllegalStateException
		try {
			myQueue.add("Thursday");
			myQueue.add("Friday");
			myQueue.add("Weekend");
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}
		
		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) {
			e.printStackTrace();
		}
		
		// 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.

Output:

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close