Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Collection add() Method in Java with Examples
Next article icon

Collection add() Method in Java with Examples

Last Updated : 07 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Syntax: 

Collection.add(E element)

Parameters: This method accepts a mandatory parameter element of type E which is to be added to this collection.

Return Value: 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 following 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

Now we will be implementing this method over different classes as it is a very important and essential method when it comes downs to java programming so here we will be stressing over each class as follows:

  • LinkedList class
  • ArrayDeque
  • ArrayList class
  • NullPointerException is Thrown

Let us implement add() method in all 4 above listed cases via clean java examples as follows:

Example 1: LinkedList Class

Java
// Java code to illustrate boolean add() method  import java.io.*; import java.util.*;  public class GFG {     public static void main(String args[])     {          // creating an empty LinkedList         Collection<String> list = new LinkedList<String>();          // use add() method to add elements in the list         list.add("Geeks");         list.add("for");         list.add("Geeks");          // Output the present list         System.out.println("The list is: " + list);          // Adding new elements to the end         list.add("Last");         list.add("Element");          // printing the new list         System.out.println("The new List is: " + list);     } } 

Output: 
The list is: [Geeks, for, Geeks] The new List is: [Geeks, for, Geeks, Last, Element]

 

Example 2: ArrayDeque Class 

Java
// Java code to illustrate add() method  import java.util.*;  public class ArrayDequeDemo {     public static void main(String args[])     {         // Creating an empty ArrayDeque         Collection<String> de_que = new ArrayDeque<String>();          // Use add() method to add elements into the Deque         de_que.add("Welcome");         de_que.add("To");         de_que.add("Geeks");         de_que.add("4");         de_que.add("Geeks");          // Displaying the ArrayDeque         System.out.println("ArrayDeque: " + de_que);     } } 

Output: 
ArrayDeque: [Welcome, To, Geeks, 4, Geeks]

 

Example 3: Using ArrayList Class 

Java
// Java code to illustrate add() method  import java.io.*; import java.util.*;  public class ArrayListDemo {     public static void main(String[] args)     {          // create an empty array list with an initial capacity         Collection<Integer> arrlist = new ArrayList<Integer>(5);          // use add() method to add elements in the list         arrlist.add(15);         arrlist.add(20);         arrlist.add(25);          // prints all the elements available in list         for (Integer number : arrlist) {             System.out.println("Number = " + number);         }     } } 

Output: 
Number = 15 Number = 20 Number = 25

 

Geeks do keep an bound over special case where NullPointer Exception will be thrown as show in below example as follows:

Example 4:

Java
// Java code to illustrate boolean add() // Where NullPointerException is Thrown   // Importing required utility classes import java.util.*;  // Main class // LinkedListDemo class GFG {      // Main driver method     public static void main(String args[])     {          // Creating an empty ArrayList of string type         Collection<String> list = new ArrayList<String>();          // Printing and displaying the Arraylist         System.out.println("The ArrayList is: " + list);          // Note: Here by now we have not added any element/s          // Try block to check for exceptions         try {              // Appending the null to the list             // using add() method             list.add(null);         }          // Catch block to handle exceptions         catch (Exception e) {              // Display message when exceptions occurs             System.out.println("Exception: " + e);         }     } } 

Output: 
The ArrayList is: []

 

Output explanation: Here we need to pick it up as we will only receive a List. So it is good practice to document for add() method either it is accepting it whether it needs to support null.


Next Article
Collection add() Method in Java with Examples

R

RishabhPrabhu
Improve
Article Tags :
  • Java
  • Java-Collections
  • Java - util package
  • Java-Functions
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    Collection addAll() method in Java with Examples
    The addAll(Collection collection) of java.util.Collection interface is used to add the Collection 'collection' to this existing collection. This method returns a boolean value depicting the successfulness of the operation. If the collection was added, it returns true, else it returns false. Syntax:
    3 min read
    Collections addAll() method in Java with Examples
    The addAll() method of java.util.Collections class is used to add all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this
    3 min read
    Collection clear() method in Java with Examples
    The collection clear() method of Java Collection Interface clears the Collection upon which it is called. After this method is called, the collection will be empty as it removes all the elements from the collection. This method does not take any parameter and does not return any value. Example: Java
    3 min read
    Collections min() method in Java with Examples
    min(Collection<? extends T> coll) The min() method of java.util.Collections class is used to return the minimum element of the given collection, according to the natural ordering of its elements. All elements in the collection must implement the Comparable interface. Furthermore, all elements
    4 min read
    Collections list() method in Java with Examples
    The list() method of java.util.Collections class is used to return an array list containing the elements returned by the specified enumeration in the order they are returned by the enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that requi
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences