BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java ArrayList add Method with Examples

Last Updated: September 17, 2022 by Chaitanya Singh | Filed Under: java

The add() method of Java ArrayList class is used to add elements to an ArrayList. In this guide, we will see various examples of add method.

Syntax

1. To add element at the end of the list:

public boolean add (E element)

2. To add elements at a specific position:

public void add(int index, Object element)

Java ArrayList add Method Examples

Let’s see examples to understand how the add method works:

1. Adding element at the end of the list

This is the basic program, here we are just calling the add method to add new elements to the end of the ArrayList.

import java.util.ArrayList;
public class JavaExample{
  public static void main(String[] args) {
    ArrayList<String> arrList = new ArrayList<>();
    arrList.add("Ram");   // [Ram]
    arrList.add("Steve"); // [Ram, Steve]
    arrList.add("John");   // [Ram, Steve, John]
    System.out.println(arrList);
  }
}

Output:

[Ram, Steve, John]

2. Adding an element to the beginning of ArrayList

You can add the element to the beginning of ArrayList by calling add method like this: add(0, Element). ArrayList is based on zero based indexing, which means first element is present at the index 0. The other elements in the ArrayList are shifted, which means after adding new element to the front, the first element becomes second, second element becomes third and so on.

import java.util.ArrayList;
public class JavaExample{
  public static void main(String[] args) {
    ArrayList<String> arrList = new ArrayList<>();
    arrList.add("Ram");   // [Ram]
    arrList.add("Steve"); // [Ram, Steve]
    arrList.add("John");   // [Ram, Steve, John]

    // instead of adding the element at the end, we are
    // adding the element in the beginning using
    // add(int index, Object element) method variation
    arrList.add(0, "Chaitanya");

    System.out.println(arrList);
  }
}

Output:

[Chaitanya, Ram, Steve, John]

3. Add element in ArrayList if it doesn’t exist

For this example, we are using another ArrayList method contains(), which checks if the element already present in the arraylist or not. It returns true, if element exists else returns false.

import java.util.Scanner;
import java.util.ArrayList;
public class JavaExample{
  public static void main(String[] args) {
    ArrayList<Integer> arrList = new ArrayList<>();
    arrList.add(1);
    arrList.add(10);
    arrList.add(5);

    System.out.print("Enter an integer number: ");
    Scanner scan = new Scanner(System.in);
    int temp = scan.nextInt();

    //checking if element exists
    //add element if doesn't exist
    if(arrList.contains(temp)){
      System.out.println("The entered element already present");
    }else{
      arrList.add(temp);
      System.out.println("Entered element added to the list");
    }

    System.out.println("ArrayList elements: "+arrList);
  }
}

Output 1: If user enters an element that already exists
Add element to arraylist if not exists
Output 2: If user enters an element that doesn’t exist
ArrayList add method example

4. Adding null values to ArrayList

In this example, we are adding null values to the ArrayList, which is perfectly fine. However if you only want to iterate non-null values then you can do it like this:

import java.util.ArrayList;
public class JavaExample{
  public static void main(String[] args) {
    ArrayList<Integer> arrList = new ArrayList<>();
    arrList.add(1);
    arrList.add(10);
    arrList.add(5);
    arrList.add(null); //adding null

    System.out.println("ArrayList elements: "+arrList);

    System.out.println("ArrayList not-null elements: ");
    //if only want to print elements that are not null
    for (Integer item : arrList) {
      if (item != null)
        System.out.println(item);
    }
  }
}

Output:
ArrayList adding null values

5. ArrayList IndexOutOfBoundsException

The reason the following program throws IndexOutOfBoundsException is: The ArrayList grows in size dynamically, you cannot add third element in the ArrayList without adding the second element, which is what we are trying to do in the following program.

import java.util.ArrayList;
public class JavaExample{
  public static void main(String[] args){
    ArrayList<String> list = new ArrayList<>();
    list.add(0, "Hi");  // ["Hi"]
    list.add(0, "Hello");// ["Hello", "Hi"]

    // throws IndexOutOfBoundsException
    list.add(3, "Bye");
  }
}

Output:

IndexOutOfBoundsException
❮ Java ArrayListJava Collections ❯

Top Related Articles:

  1. Add Multiple Items to an ArrayList in Java
  2. How to get the last element of Arraylist?
  3. Difference between ArrayList and Vector in Java
  4. How to loop ArrayList in Java
  5. Convert a Set of String to a comma separated String in Java

Tags: Collections, Java-ArrayList

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Samira kumar Biswal says

    September 14, 2017 at 6:53 PM

    In Collection Topics,please provide how all the collection classes and interfaces also Map classes and interfaces internally works and which algorithm it follws.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap