add() method in Java

It Inserts the specified element to the end of the queue if there is space, returning true upon success and throwing an IllegalStateException if no space is currently available. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false.

Exceptions: This method throws 5 exceptions listed below as follows:

  • UnsupportedOperationException: if the add operation is not supported by this collection
  • ClassCastException: if the class of the specified element prevents it from being added to this collection
  • NullPointerException: if the specified element is null and this collection does not permit null elements
  • IllegalArgumentException: if some property of the element prevents it from being added to this collection
  • IllegalStateException: if the element cannot be added at this time due to insertion restrictions

Below is the Implementation of add() method in java:

Java




// add() method:
  
import java.util.*;
  
public class Main {
    public static void main(String[] args)
    {
        // Creating Queue using the LinkedList
        Queue<Integer> numbers = new LinkedList<>();
  
        // Insert element at the rear of the queue
        // using add method
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        System.out.println("Queue using add method: "
                           + numbers);
    }
}


Output

Queue using add method: [1, 2, 3]

If the element cannot be added at this time due to insertion restrictions:

Java




import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        ArrayList<String> nums = new ArrayList<String>();
  
        // Adding Elements
        nums.add("CS");
        nums.add("Mech");
        nums.add("Electrical");
  
        Iterator<String> itr = nums.iterator();
        itr.remove();
    }
}


Output:
Exception in thread "main" java.lang.IllegalStateException
    at java.base/java.util.ArrayList$Itr.remove(ArrayList.java:1010)
    at GFG.main(GFG.java:13)

Difference between add() and offer() methods in Queue in Java

Add() and Offer() are the methods used for adding the elements in the Queue. But both have their main function and they treat the elements differently.

Similar Reads

add() method in Java:

It Inserts the specified element to the end of the queue if there is space, returning true upon success and throwing an IllegalStateException if no space is currently available. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false....

Offer() method in Java:

...

Difference between add() and offer() method in java

...