CodeBlanks Logo Icon CodeBlanks

add and get

Learn collection operations with add() and get().

Adding and reading: add and get

You use add to put an element into an ArrayList and get to read one. get takes a zero-based index.

ArrayList<String> fruits = new ArrayList<>();
fruits.add("Elma");
fruits.add("Armut");
String first = fruits.get(0);
// first = "Elma"

If the index is out of range, IndexOutOfBoundsException is thrown. That is why checking with size before calling get is safer.

Iterating the list with a loop

A for-each loop is very handy for walking the list. The String type appears in the loop variable; elements come one by one.

for (String name : names) {
  System.out.println(name);
}

You can also use the classic for (int i = 0; i < list.size(); i++) form; this is essential when you need the index (for example to call set).

Practice Print the first and last apple

From the list below, take the first and last element with get; print each on its own line.

Starter code

Main.java
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> fruits = new ArrayList<>();
    fruits.add("Elma");
    fruits.add("Armut");
    fruits.add("Muz");
    // Print the first element
    // Print the last element (size - 1)
  }
}

Sample solution

Main.java
System.out.println(fruits.get(0));
System.out.println(fruits.get(fruits.size() - 1));

Expected output

Elma
Muz

Questions and answers

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

1 Match call to result

Term Meaning
add("X") Appends X at the end
get(0) Returns the first element
size() Returns the element count
remove(0) Removes the first element

2 Fill in the blank: get the first element

Question
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Elma");
String first = fruits.____(0);
Answer
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Elma");
String first = fruits.get(0);

Explanation: get(0) returns the first element.

3 What does fruits.get(5) do when size is 3?

  • It throws IndexOutOfBoundsException
  • It returns the last element
  • It returns null Correct answer
  • It adds 5 elements to the list

Explanation: An invalid index throws an exception.

All lessons in Beginner