CodeBlanks Logo Icon CodeBlanks

Adding items

Add items with addItem.

Adding items (add)

In this lesson we'll meet the add method. cart.add(...) puts a new item at the end of the list:

ArrayList<String> cart = new ArrayList<>();
cart.add("Apple");
cart.add("Bread");
System.out.println(cart);  // [Apple, Bread]

Each add call adds one more item. Since ArrayList is dynamic, the item count does not need to be known in advance. The final cart holds all added items.

Cart size

cart.size() gives the number of items in the cart. For an empty cart it returns 0:

ArrayList<String> cart = new ArrayList<>();
System.out.println(cart.size());  // 0
cart.add("Apple");
System.out.println(cart.size());  // 1

Arrays have a length field (no parens); ArrayList has a size() method (parens). This is a common source of mistakes; be careful.

Practice Add two items and print

Add two items to the cart from the previous lesson. Add cart.add("Apple") and cart.add("Bread"). Print the cart and its size with System.out.println(cart) and System.out.println(cart.size()).

Starter code

Main.java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> cart = new ArrayList<>();
        // Add two items here
        System.out.println(cart);
    }
}

Sample solution

Main.java
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> cart = new ArrayList<>();
        cart.add("Apple");
        cart.add("Bread");
        System.out.println(cart);
        System.out.println(cart.size());
    }
}

Expected output

[Apple, Bread]
2

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the add call

Question
cart.____("Apple");
Answer
cart.add("Apple");

Explanation: cart.add("Apple") adds Apple to the cart.

2 What does cart.add("Apple") do?

  • Removes Apple from the cart
  • Adds Apple to the cart Correct answer
  • Empties the cart
  • Shows Apple

Explanation: add adds an item to the list.

3 Match the list methods

Term Meaning
add Add an item
size() Item count
cart Cart variable
println Print

All lessons in Beginner