Java .add()

BrandonDusch's avatar
Published Mar 21, 2022Updated Mar 21, 2022
Contribute to Docs

The .add() method is used for adding elements to instances of the ArrayList class.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

An element can be added to an instance of ArrayList by being passed to the .add() method:

arrayListInstance.add(element);

Example

import java.util.ArrayList;
public class Students {
public static void main(String[] args) {
// Create an ArrayList called studentList, which initially holds []
ArrayList<String> studentList = new ArrayList<String>();
// Add students to the ArrayList
studentList.add("John");
studentList.add("Lily");
studentList.add("Samantha");
studentList.add("Tony");
System.out.println(studentList);
}
}

The output from the snippet above would look like this:

[John, Lily, Samantha, Tony]

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours