Difference between peek poll and remove method of the Queue interface in Java?

Peek() - It will give the head element of the queue. If queue is empty then it will return null.

Poll() - It will give the head element of the queue and will remove the head element from queue. If queue is empty then it will return null.

Remove() - It will give the head element of the queue and will remove the head element from queue. If queue is empty then it will throw an Exception.

Let's have a look at following piece of code.

import java.util.LinkedList;
import java.util.Queue;
 
public class Test 
{ 
    public static void main(String args[]) {
        Queue<Integer> queue = new LinkedList<Integer>();
 
        queue.add(100);
        queue.add(200);
 
        System.out.println("Peek = " + queue.peek());
        System.out.println("Queue size = " + queue.size());
 
        System.out.println("poll = " + queue.poll());
        System.out.println("Queue size = " + queue.size());
 
        System.out.println("remove = " + queue.remove());
        System.out.println("Queue size = " + queue.size());
 
        //calling the methods on empty queue, to test the null return value and exception throw
        System.out.println("Peek = " + queue.peek());
        System.out.println("poll = " + queue.poll());
        System.out.println("remove = " + queue.remove());
    }
} 
 
Output:
Peek = 100
Queue size = 2
poll = 100
Queue size = 1
remove = 200
Queue size = 0
Peek = null
poll = null
Exception in thread "main" java.util.NoSuchElementException
	at java.util.LinkedList.removeFirst(LinkedList.java:270)
	at java.util.LinkedList.remove(LinkedList.java:685)
	at Test.main(Test.java:24)

Hope you have enjoyed reading Difference between peek poll and remove method of the Queue interface in Java?. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.