Saturday, December 13, 2025
HomeLanguagesJavaPriorityBlockingQueue put() method in Java

PriorityBlockingQueue put() method in Java

The put(E e) method of PriorityBlockingQueue is used to add an element into this queue. This method inserts the specified element into this priority queue. Since the queue is unbounded, this method will be never be blocked.
Syntax: 
 

public void put(E e)

Parameter: This method accepts a mandatory parameter e which is the element to be inserted in PriorityBlockingQueue.
Return Value: The method does not return anything.
Exception: This method throws following exceptions: 
 

  • ClassCastException – if the specified element cannot be compared with elements currently in the priority queue according to the priority queue’s ordering.
  • NullPointerException – if the specified element is null.

Below programs illustrate put() method in PriorityBlockingQueue:
Program 1:
 

Java




// Java Program Demonstrate put(E e)
// method of PriorityBlockingQueue
 
import java.util.concurrent.PriorityBlockingQueue;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create object of PriorityBlockingQueue
        PriorityBlockingQueue<Integer> pbq
            = new PriorityBlockingQueue<Integer>();
 
        // Add element using put() method
        pbq.put(1);
        pbq.put(2);
        pbq.put(3);
        pbq.put(4);
 
        // print elements of queue
        System.out.println("Queue: " + pbq);
    }
}


Output: 

Queue: [1, 2, 3, 4]

 

Program 2: To demonstrate NullPointerException
 

Java




// Java Program Demonstrate put(E e)
// method of PriorityBlockingQueue
 
import java.util.concurrent.PriorityBlockingQueue;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // create object of PriorityBlockingQueue
        PriorityBlockingQueue<String> pbq
            = new PriorityBlockingQueue<String>();
 
        // try to put null value in put method
        try {
            pbq.put(null);
        }
        catch (Exception e) {
            // print error details
            System.out.println("Exception: " + e);
        }
    }
}


Output: 

Exception: java.lang.NullPointerException

 

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32446 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6814 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12030 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7199 POSTS0 COMMENTS
Thapelo Manthata
6896 POSTS0 COMMENTS
Umr Jansen
6882 POSTS0 COMMENTS