Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

add()

Example

Append an item to a list.

import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars);
  }
}

Definition and Usage

The add() method appends an item to the list.

If an index is specified, the new item will be inserted at that position, shifting all subsequent elements in the list one position forward.

If no index is specified, the new item will be added to the end of the list.

Syntax

Choose one of the following:

public boolean add(T item)
public void add(int index, T item)

T represents the data type of the items in the list.

Parameter Values

Parameter

Description

index

Optional: The position in the list where the item should be added.

item

Required: The item that will be added to the list.

Technical Details

Returns:

If an index is specified, the method returns nothing. When no index is specified, it returns true if the list is altered and false if the list remains unchanged.

Throws

IndexOutOfBoundsException occurs if the index is negative or exceeds the list’s size.

More Examples

Example

Insert an item at a specific position within the list.

import java.util.ArrayList;
public class Main { 
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    cars.add(2, "Toyota");
   
    System.out.println(cars);
  }
}