Collection add() method in Java with Examples
The add(E element) of java.util.Collection interface is used to add the element ‘element’ to this collection. This method returns a boolean value depicting the successfulness of the operation. If the element was added, it returns true, else it returns false.
Parameters: This method accepts a mandatory parameter element of type E which is to be added to this collection.
Return Value: 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 following exceptions:
- 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 examples illustrate the Collection add() method:
Example 1: Using LinkedList Class
The list is: [Geeks, for, Geeks] The new List is: [Geeks, for, Geeks, Last, Element]
Example 2: Using ArrayDeque Class
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]
Example 3: Using ArrayList Class
Number = 15 Number = 20 Number = 25
Example 4: To demonstrate NullPointer Exception
The ArrayList is: 
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.