Java Arena
Step 1 of 8

Creating a list

Say a program reads the names of everyone coming to a party. With one variable per name, you'd need name1, name2, name3 and so on, and you'd have to know in advance how many guests there will be. A list solves both problems: it's one variable that holds any number of values, in order.

Java's list is called ArrayList:

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> planets = new ArrayList<>();
        planets.add("Mercury");
        planets.add("Venus");
        planets.add("Earth");
        System.out.println(planets);
    }
}
Output
[Mercury, Venus, Earth]
  • import java.util.ArrayList; goes at the very top, like the import for Scanner. Without it, Java doesn't know the name ArrayList.
  • ArrayList<String> planets declares a variable for a list of Strings. The type between < and > says what kind of values the list holds.
  • new ArrayList<>() creates a new, empty list, and = stores it in the variable.
  • planets.add("Mercury") adds a value at the end of the list. The list grows by one each time; there's no size to set in advance.
  • Printing a list prints all its values in square brackets, separated by commas, in the order they were added. An empty list prints [].

A list can hold the same value more than once. And + joins a list to text, just as it does a number: "Planets: " + planets gives Planets: [Mercury, Venus, Earth].

Your task

Challenge 1 of 3

Fill in the blanks so the program creates a list, adds three drinks to it, and prints:

[tea, coffee, cocoa]

Challenge 2

What does this program print? Type each line.

Challenge 3

Read the titles of books you'd like to read, one per line, until the line stop. Add each title to the list books (but not stop itself). After the loop, print Reading list: followed by the list. For the input Dune, Emma, Beloved and stop the program prints:

Reading list: [Dune, Emma, Beloved]