LinkedTransferQueue add() method in Java
Last Updated :
14 Sep, 2018
The add() method of java.util.concurrent.LinkedTransferQueue is an in-built function in Java which is used to insert an element in this queue.
Syntax:
LinkedTransferQueue.add(E e)
Parameters: The function accepts a single parameter e i.e. the element to be inserted.
Return Value: The function returns a boolean value.
Exception: The function throws NullPointerException when the specified element is Null.
Below programs illustrate the use of java.util.concurrent.LinkedTransferQueue.add() :
Program 1: Inserting Integers in the queue.
import java.util.concurrent.*;
class LinkedTransferQueueAddExample1 {
public static void main(String[] args)
{
LinkedTransferQueue<Integer>
queue = new LinkedTransferQueue<Integer>();
for ( int i = 10 ; i <= 15 ; i++)
queue.add(i);
System.out.println( "The elements in the queue are:" );
for (Integer i : queue)
System.out.print(i + " " );
}
}
|
Output:
The elements in the queue are:
10 11 12 13 14 15
Program 2: Adding String in the queue.
import java.util.concurrent.*;
class LinkedTransferQueueAddExample2 {
public static void main(String[] args)
{
LinkedTransferQueue<String>
queue = new LinkedTransferQueue<String>();
queue.add( "a" );
queue.add( "b" );
queue.add( "c" );
queue.add( "d" );
queue.add( "e" );
System.out.println( "The elements in the queue are:" );
for (String i : queue)
System.out.print(i + " " );
}
}
|
Output:
The elements in the queue are:
a b c d e
Program 3: To demonstrate NullPointerException
import java.util.concurrent.*;
class LinkedTransferQueueAddExample2 {
public static void main(String[] args)
{
LinkedTransferQueue<String>
queue = new LinkedTransferQueue<String>();
try {
queue.add( null );
}
catch (Exception e) {
System.out.println( "Exception: " + e);
}
}
}
|
Output:
Exception: java.lang.NullPointerException
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/LinkedTransferQueue.html#add(E)
Share your thoughts in the comments
Please Login to comment...