Part 1 · The core language

7Arrays and ArrayList

Every variable you have used so far holds one value. Real programs hold collections: the scores of a class, the words typed on the command line (the line you type in the terminal), the names on a waiting list. This lesson introduces the two ways Java stores a collection, the fixed-size array and the growable ArrayList, and finishes the explanation of public static void main(String[] args) that lesson 1 promised.

By the end you will be able to

  • create an array, read and change its elements, and loop over it with an indexed for and with for-each
  • explain why two array variables can name one array, and why a method can change the array it was given
  • use Arrays.toString, Arrays.equals, Arrays.copyOf and Arrays.sort, and say what an import line does
  • write a program that takes its input from the command line, and a method that accepts any number of arguments
  • use an ArrayList, including the wrapper types it needs for numbers, and avoid the traps that come with them
  • choose between an array and a list, and recognise the errors each one produces

Arrays: many values under one name

Suppose a program needs five test scores. Five variables, score1 to score5, would work, but you could not loop over them, and the program would have to be rewritten for six scores. What you want is one name for the whole group, and a number to say which member you mean.

That is an array: a fixed number of variables of the same type, stored together and reached through one name. Each variable in the array is an element. The number that picks an element is its index, and the count of elements is the array's length.

int[] scores = new int[5];

Read this from the left. int[] is a type: array of int. scores is the variable. new int[5] asks Java to make a new array with room for five int values, the same new you used for StringBuilder in lesson 6. To reach an element you write the index in square brackets after the name.

code/m07-arrays-and-lists/ArrayBasics.java
public class ArrayBasics {
    public static void main(String[] args) {
        int[] scores = new int[5];
        scores[0] = 72;
        scores[1] = 85;
        scores[4] = 91;
        System.out.println("first: " + scores[0]);
        System.out.println("third: " + scores[2]);
        System.out.println("length: " + scores.length);
        scores[1] = scores[1] + 5;
        System.out.println("second now: " + scores[1]);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac ArrayBasics.java
> java ArrayBasics
first: 72
third: 0
length: 5
second now: 90

Three facts are visible here.

code/m07-arrays-and-lists/DefaultValues.java (lines 3 to 12)
int[] counts = new int[2];
double[] prices = new double[2];
boolean[] flags = new boolean[2];
char[] letters = new char[2];
String[] names = new String[2];
System.out.println(counts[0]);
System.out.println(prices[0]);
System.out.println(flags[0]);
System.out.println((int) letters[0]);
System.out.println(names[0]);
Terminal, in code/m07-arrays-and-lists
> javac DefaultValues.java
> java DefaultValues
0
0.0
false
0
null
Element typeDefaultSeen above
numeric types (int, double, long and so on)zero0 and 0.0
booleanfalsefalse
charthe character whose code is 0, which has no visible formcasting it to int printed 0
objects such as Stringnull, meaning no object yetnull

The last row matters. An array of String starts as a row of nulls, not a row of empty strings. You met null in lesson 6; this is the most common way to meet it again.

Predict

What does this program print?

code/m07-arrays-and-lists/predict/DefaultsPredict.java (lines 3 to 5)
String[] words = new String[3];
words[1] = "hi";
System.out.println(words.length + " " + words[0] + " " + words[1]);
Reveal the answer
Terminal, in code/m07-arrays-and-lists/predict
> javac DefaultsPredict.java
> java DefaultsPredict
3 null hi

3 null hi. The array has three elements however many you fill in. Only position 1 was assigned, so position 0 still holds null, and string concatenation turns null into the text null.

Creating an array from known values

When you already know the values, list them in braces. Java counts them and sets the length for you. The length in new int[size] can be any int expression, including a variable, as long as it is not negative. Once the array exists its length never changes.

code/m07-arrays-and-lists/Initialiser.java (lines 3 to 14)
int[] primes = {2, 3, 5, 7, 11};
String[] days = {"Mon", "Tue", "Wed"};
System.out.println(primes.length);
System.out.println(days.length);
System.out.println(days[2]);

String word = "elephant";
System.out.println(word.length());

int size = 3 + 4;
double[] readings = new double[size];
System.out.println(readings.length);
Terminal, in code/m07-arrays-and-lists
> javac Initialiser.java
> java Initialiser
5
3
Wed
8
7

Length is a field, not a method call

Compare days.length with word.length() in that program. An array's length is a field: a value stored inside the array object and read with a dot, with no parentheses. A String's length is a method call, so it has parentheses. Lesson 8 explains fields properly. For now, remember that mixing them up is a compile-time error, and that the compiler's message tells you which way round you went.

code/m07-arrays-and-lists/broken/LengthParens.java
public class LengthParens {
    public static void main(String[] args) {
        int[] scores = {72, 85, 91};
        System.out.println(scores.length());
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac LengthParens.java
LengthParens.java:4: error: cannot find symbol
        System.out.println(scores.length());
                                 ^
  symbol:   method length()
  location: variable scores of type int[]
1 error
code/m07-arrays-and-lists/broken/StringLengthField.java
public class StringLengthField {
    public static void main(String[] args) {
        String word = "elephant";
        System.out.println(word.length);
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac StringLengthField.java
StringLengthField.java:4: error: cannot find symbol
        System.out.println(word.length);
                               ^
  symbol:   variable length
  location: variable word of type String
1 error

Both are cannot find symbol, which lesson 1 taught you to read: you used a name that does not exist here. The extra lines say what kind of name it was (method length() or variable length) and what it was being looked up on. length() does not exist on an int[], and length without parentheses does not exist on a String.

Going past the end

An index must lie between 0 and length - 1. The compiler does not check this, because the index is often calculated while the program runs. The JVM checks every access, and a bad index stops the program.

code/m07-arrays-and-lists/OffByOne.java
public class OffByOne {
    public static void main(String[] args) {
        int[] scores = {72, 85, 91};
        for (int i = 0; i <= scores.length; i++) {
            System.out.println("score " + i + " is " + scores[i]);
        }
        System.out.println("done");
    }
}
Terminal, in code/m07-arrays-and-lists
> javac OffByOne.java
> java OffByOne
score 0 is 72
score 1 is 85
score 2 is 91
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
	at OffByOne.main(OffByOne.java:5)

Read the report as lesson 1 taught: what, then where. ArrayIndexOutOfBoundsException is the kind of failure. Index 3 out of bounds for length 3 gives the index the program asked for and the length of the array, and from those two numbers you can see the mistake at once: valid indexes were 0, 1 and 2. The at line says line 5, the statement that used scores[i]. The loop ran correctly three times, then i reached 3 because the condition used <=. With arrays the condition is nearly always i < scores.length.

A negative index fails in the same way:

code/m07-arrays-and-lists/NegativeIndex.java (lines 3 to 5)
int[] scores = {72, 85, 91};
int position = -1;
System.out.println(scores[position]);
Terminal, in code/m07-arrays-and-lists
> javac NegativeIndex.java
> java NegativeIndex
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
	at NegativeIndex.main(NegativeIndex.java:5)

An array is an object: names and references

Lesson 6 showed that a String variable does not contain the text. It contains a reference to a String object that lives elsewhere. Arrays work the same way. For now, an object means a thing that lives in its own block of memory and is reached through a reference; lesson 8 gives the full definition. An array is an object, so int[] scores is a variable that holds a reference to the array, not the array itself.

That has a consequence that surprises almost everyone the first time. Compare what happens when you copy a plain number with what happens when you copy an array variable.

code/m07-arrays-and-lists/Alias.java (lines 3 to 11)
int x = 5;
int y = x;
y = 6;
System.out.println("x = " + x + ", y = " + y);

int[] a = {1, 2, 3};
int[] b = a;
b[0] = 99;
System.out.println("a[0] = " + a[0] + ", b[0] = " + b[0]);
Terminal, in code/m07-arrays-and-lists
> javac Alias.java
> java Alias
x = 5, y = 6
a[0] = 99, b[0] = 99
A PRIMITIVE: THE VARIABLE HOLDS THE VALUE x 5 y 6 int y = x; copied the number. Two separate boxes. AN ARRAY: THE VARIABLE HOLDS A REFERENCE a b one array object 99 2 3 0 1 2 int[] b = a; copied the reference. Two names, one array.

The lower half of the diagram is the whole story. int[] b = a; copies what is inside a, and what is inside a is a reference. No second array was made. After the assignment, a and b are two names for the same array, which is called an alias. Changing an element through b changes what you see through a, because there is only one array to see.

Assigning to the variable itself is different from assigning to an element. b = something makes b refer to something else and leaves the old array, and a, alone. To write a new array into an existing variable you need a creation expression, new int[] {7, 8, 9}: new, the type, and then the values. The short form int[] x = {7, 8, 9}; is allowed only in a declaration.

Predict

Work out each variable's contents with a diagram before you answer. What does this print?

code/m07-arrays-and-lists/predict/AliasPredict.java (lines 3 to 8)
int[] a = {10, 20, 30};
int[] b = a;
a[1] = 99;
b = new int[] {7, 8, 9};
b[0] = 0;
System.out.println(a[0] + " " + a[1] + " " + b[0] + " " + b[1]);
Reveal the answer
Terminal, in code/m07-arrays-and-lists/predict
> javac AliasPredict.java
> java AliasPredict
10 99 0 8

10 99 0 8. After b = a both names reach the array {10, 20, 30}, so a[1] = 99 makes it {10, 99, 30}. Then b = new int[] {7, 8, 9} builds a second array and points b at it. From then on a and b are unrelated. b[0] = 0 changes only the new array, giving {0, 8, 9}. So a[0] is 10, a[1] is 99, b[0] is 0 and b[1] is 8.

An array stays in existence for as long as something can still reach it through a reference. That fact makes returning arrays from methods work, as you will see in Arrays and methods.

Looping over an array

Arrays and loops belong together. The standard way to visit every element uses the loop from lesson 4, with the index as the counter.

code/m07-arrays-and-lists/ForLoops.java (lines 3 to 11)
String[] colours = {"red", "green", "blue"};

for (int i = 0; i < colours.length; i++) {
    System.out.println(i + ": " + colours[i]);
}

for (String colour : colours) {
    System.out.println(colour);
}
Terminal, in code/m07-arrays-and-lists
> javac ForLoops.java
> java ForLoops
0: red
1: green
2: blue
red
green
blue

The first loop starts at 0 and stops when i is no longer less than colours.length, so i takes exactly the valid indexes. The second loop is the for-each loop. Read for (String colour : colours) as for each colour in colours. On every pass the variable colour holds the next element, in order, from the first to the last. There is no counter, no condition and no [i], so there is nothing to get wrong by one.

That simplicity has a price. The for-each loop cannot do two things:

Predict

The first loop below assigns to score on every pass. What does the loop's own println show? What does the line after the loop show for the array? And what does the line after the second loop show?

code/m07-arrays-and-lists/ForEachCopy.java (lines 3 to 14)
int[] scores = {10, 20, 30};

for (int score : scores) {
    score = score * 2;
    System.out.println("inside: " + score);
}
System.out.println(scores[0] + " " + scores[1] + " " + scores[2]);

for (int i = 0; i < scores.length; i++) {
    scores[i] = scores[i] * 2;
}
System.out.println(scores[0] + " " + scores[1] + " " + scores[2]);
Reveal the answer
Terminal, in code/m07-arrays-and-lists
> javac ForEachCopy.java
> java ForEachCopy
inside: 20
inside: 40
inside: 60
10 20 30
20 40 60

Inside the loop score really was doubled, which is why inside: 20, inside: 40 and inside: 60 appear. But the array still reads 10 20 30, because each pass changed only a copy of an element. The second loop does the job properly with an indexed loop, scores[i] = scores[i] * 2;, and the array becomes 20 40 60. To change the contents of an array you need the index.

Use for-each when you only read, and an indexed loop when you need the position or must write. Either way, the lesson 4 patterns carry over unchanged. Each one below is a loop over an array.

code/m07-arrays-and-lists/Patterns.java
public class Patterns {
    public static void main(String[] args) {
        int[] scores = {72, 85, 91, 60, 85, 78};

        int sum = 0;
        for (int score : scores) {
            sum += score;
        }
        double average = (double) sum / scores.length;
        System.out.println("sum " + sum + ", average " + average);

        int largest = scores[0];
        for (int score : scores) {
            if (score > largest) {
                largest = score;
            }
        }
        System.out.println("largest " + largest);

        int passes = 0;
        for (int score : scores) {
            if (score >= 75) {
                passes++;
            }
        }
        System.out.println("scores of 75 or more: " + passes);

        int target = 85;
        int found = -1;
        for (int i = 0; i < scores.length; i++) {
            if (scores[i] == target) {
                found = i;
                break;
            }
        }
        System.out.println("first " + target + " is at position " + found);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac Patterns.java
> java Patterns
sum 471, average 78.5
largest 91
scores of 75 or more: 4
first 85 is at position 1

The library's array helpers, and your first import

What happens if you print an array directly?

code/m07-arrays-and-lists/PrintDirect.java (lines 3 to 6)
int[] scores = {72, 85, 91};
String[] colours = {"red", "green"};
System.out.println(scores);
System.out.println(colours);
Terminal, in code/m07-arrays-and-lists
> javac PrintDirect.java
> java PrintDirect
[I@1dbd16a6
[Ljava.lang.String;@251a69d7

Not the contents. What you get is a code for the type, then an @, then a number that identifies that particular array object. [I stands for array of int and [Ljava.lang.String; for array of String. The text after the @ is an identity code written with digits and the letters a to f. It can be different on another machine or another Java version, so nothing should rely on it. For arrays of numbers or strings this text is never useful, and seeing it in your output means you printed an array when you meant to print its contents. There is one exception: println has a special case for an array of char, and prints the characters themselves.

code/m07-arrays-and-lists/CharPrint.java
public class CharPrint {
    public static void main(String[] args) {
        char[] letters = {'h', 'i'};
        System.out.println(letters);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac CharPrint.java
> java CharPrint
hi

The rest of this section is about all the other kinds of array. Lesson 9, which covers toString, explains where the [I@ text comes from.

The standard library has a class full of array tools for exactly this. It is called Arrays, and using it needs something new.

Packages and import

The standard library has thousands of classes, and they are sorted into named groups called packages. The full name of a class is its package name, a dot, and its own name. String, System, Math and Integer live in the package java.lang, and Java imports that one for you automatically, which is why you have never had to ask for them. Everything else must be requested, and Arrays is in the package java.util. Here is what happens if you forget:

code/m07-arrays-and-lists/broken/NoImport.java
public class NoImport {
    public static void main(String[] args) {
        int[] scores = {72, 85, 91};
        System.out.println(Arrays.toString(scores));
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac NoImport.java
NoImport.java:4: error: cannot find symbol
        System.out.println(Arrays.toString(scores));
                           ^
  symbol:   variable Arrays
  location: class NoImport
1 error

It is cannot find symbol again: the compiler looked for something called Arrays and found nothing. (It says variable because a name followed by a dot could be a variable; the guess is wrong but the diagnosis is right.) The fix is an import line, written above the class:

code/m07-arrays-and-lists/ToStringDemo.java (lines 1 to 3)
import java.util.Arrays;

public class ToStringDemo {

import java.util.Arrays; tells the compiler that when you write Arrays, you mean the class java.util.Arrays. An import copies nothing and costs nothing at run time. It is only a shortcut for a long name. You could skip it and write the full name each time:

code/m07-arrays-and-lists/FullName.java
public class FullName {
    public static void main(String[] args) {
        int[] scores = {72, 85, 91};
        System.out.println(java.util.Arrays.toString(scores));
    }
}

A second form of import takes everything in a package. The star means every class in this package:

code/m07-arrays-and-lists/WildcardImport.java
import java.util.*;

public class WildcardImport {
    public static void main(String[] args) {
        int[] scores = {72, 85, 91};
        System.out.println(Arrays.toString(scores));
    }
}
Terminal, in code/m07-arrays-and-lists
> javac FullName.java WildcardImport.java
> java FullName
[72, 85, 91]
> java WildcardImport
[72, 85, 91]

The two programs make the same call, Arrays.toString(scores), on the same array. FullName writes the full name java.util.Arrays at the call, and WildcardImport imports the whole package with a star and then uses the short name. The output is identical. This course writes one import per class instead, so that you can always see where each class comes from. Lesson 12 returns to packages and explains how to make your own.

The four methods you will use most

code/m07-arrays-and-lists/ToStringDemo.java (lines 5 to 10)
int[] scores = {72, 85, 91};
String[] colours = {"red", "green"};
int[] empty = new int[0];
System.out.println(Arrays.toString(scores));
System.out.println(Arrays.toString(colours));
System.out.println(Arrays.toString(empty));
Terminal, in code/m07-arrays-and-lists
> javac ToStringDemo.java
> java ToStringDemo
[72, 85, 91]
[red, green]
[]

Arrays.toString turns an array into readable text: square brackets, elements separated by commas. An empty array gives []. It is a static method, called on the class name as you call Math.max, and it works for arrays of numbers, strings and the other element types you have met. (A table, which is an array of arrays, needs a different method, shown in the section on tables.)

Next, comparing. In lesson 6, == on two String variables compared references, not contents. Arrays behave the same way.

code/m07-arrays-and-lists/EqualsDemo.java (lines 5 to 10)
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
int[] c = a;
System.out.println(a == b);
System.out.println(Arrays.equals(a, b));
System.out.println(a == c);
Terminal, in code/m07-arrays-and-lists
> javac EqualsDemo.java
> java EqualsDemo
false
true
true

The three lines print false, true and true. a == b is false: they are two different arrays that happen to hold the same numbers. Arrays.equals(a, b) is true because it compares the elements one by one. a == c is true because c = a made an alias. To ask do these hold the same values?, use Arrays.equals.

Third, copying. Arrays.copyOf(original, newLength) builds a new array of the length you ask for and fills it from the original. Since you cannot grow an array, this is how you get a bigger or smaller one.

code/m07-arrays-and-lists/CopyDemo.java (lines 5 to 13)
int[] original = {5, 6, 7};
int[] same = Arrays.copyOf(original, original.length);
int[] shorter = Arrays.copyOf(original, 2);
int[] longer = Arrays.copyOf(original, 5);
same[0] = 99;
System.out.println("original " + Arrays.toString(original));
System.out.println("same     " + Arrays.toString(same));
System.out.println("shorter  " + Arrays.toString(shorter));
System.out.println("longer   " + Arrays.toString(longer));
Terminal, in code/m07-arrays-and-lists
> javac CopyDemo.java
> java CopyDemo
original [5, 6, 7]
same     [99, 6, 7]
shorter  [5, 6]
longer   [5, 6, 7, 0, 0]

The copy is independent: changing same[0] left original untouched. A shorter length cuts elements off the end. A longer length pads with the default value, here zero.

Last, sorting.

code/m07-arrays-and-lists/SortDemo.java (lines 5 to 11)
int[] scores = {72, 85, 60, 91};
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));

String[] names = {"mia", "Zoe", "adam"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));
Terminal, in code/m07-arrays-and-lists
> javac SortDemo.java
> java SortDemo
[60, 72, 85, 91]
[Zoe, adam, mia]

Arrays.sort rearranges the array you give it, in place, and returns nothing. That is why the program prints scores after the call and not some result. Writing int[] sorted = Arrays.sort(scores); is a natural mistake, and the compiler explains it:

code/m07-arrays-and-lists/broken/SortReturn.java
import java.util.Arrays;

public class SortReturn {
    public static void main(String[] args) {
        int[] scores = {72, 85, 60};
        int[] sorted = Arrays.sort(scores);
        System.out.println(sorted[0]);
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac SortReturn.java
SortReturn.java:6: error: incompatible types: void cannot be converted to int[]
        int[] sorted = Arrays.sort(scores);
                                  ^
1 error

void is the return type from lesson 5: the method hands back nothing, so there is nothing to put in sorted. If you need to keep the original order, copy first with Arrays.copyOf and sort the copy. Strings sort by their character codes, which is why Zoe came before adam: the capitals A to Z sort before the lower-case letters a to z. Lesson 20 shows how to sort in other ways.

Arrays and methods

Lesson 5 established that a method's parameter is a new variable, initialised with a copy of the argument, and that changing the parameter cannot affect the caller. That rule is still true. The surprise is what gets copied when the argument is an array.

code/m07-arrays-and-lists/DoubleAll.java
import java.util.Arrays;

public class DoubleAll {
    static void addOne(int number) {
        number = number + 1;
    }

    static void doubleAll(int[] values) {
        for (int i = 0; i < values.length; i++) {
            values[i] = values[i] * 2;
        }
    }

    public static void main(String[] args) {
        int n = 5;
        addOne(n);
        System.out.println("n = " + n);

        int[] scores = {10, 20, 30};
        doubleAll(scores);
        System.out.println(Arrays.toString(scores));
    }
}
Terminal, in code/m07-arrays-and-lists
> javac DoubleAll.java
> java DoubleAll
n = 5
[20, 40, 60]

addOne behaves as lesson 5 taught: the method's number is a copy of n, so n stays 5. But doubleAll changed the caller's array, and no new rule was needed. The variable scores holds a reference. Calling doubleAll(scores) copies that reference into the parameter values. Now the caller and the method each hold a reference, and both refer to the one array.

TOP OF THE STACK doubleAll(values) values main (paused at the call) scores BOTTOM OF THE STACK: main, started by the JVM the one array 10 20 30 0 1 2 values holds a copy of the reference in scores, not a copy of the array.

So Java still passes everything by value, a copy of whatever the variable holds. For an int that is the number. For an array it is the reference. Some books describe this as passing arrays by reference. That wording is misleading, and the next program shows why.

Predict

This method assigns a brand-new array to its parameter. What does main print after the call?

code/m07-arrays-and-lists/Reassign.java
import java.util.Arrays;

public class Reassign {
    static void replace(int[] values) {
        values = new int[] {0, 0, 0};
        System.out.println("inside: " + Arrays.toString(values));
    }

    public static void main(String[] args) {
        int[] scores = {10, 20, 30};
        replace(scores);
        System.out.println("after:  " + Arrays.toString(scores));
    }
}
Reveal the answer
Terminal, in code/m07-arrays-and-lists
> javac Reassign.java
> java Reassign
inside: [0, 0, 0]
after:  [10, 20, 30]

Inside the method the parameter shows [0, 0, 0], but main still has [10, 20, 30]. The assignment values = new int[] {0, 0, 0} changed only the method's own variable, which now refers to a new array. The caller's variable scores is a separate variable and still refers to the original. If arrays were truly passed by reference in the sense of sharing the caller's variable, the caller would have seen the new array.

The rule to keep: a method can change the contents of an array it receives, but it cannot change which array the caller's variable refers to. Two habits follow from it. A method that modifies its array should say so in its name (doubleAll, sortScores). A method that should leave the caller's array alone must work on a copy, made with Arrays.copyOf.

Returning an array

A method returns one value, but that value can be an array, which is how a method hands back several results. The return type is the array type.

code/m07-arrays-and-lists/Squares.java
import java.util.Arrays;

public class Squares {
    static int[] squares(int count) {
        int[] result = new int[count];
        for (int i = 0; i < count; i++) {
            result[i] = i * i;
        }
        return result;
    }

    public static void main(String[] args) {
        int[] firstFive = squares(5);
        System.out.println(Arrays.toString(firstFive));
        System.out.println(squares(0).length);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac Squares.java
> java Squares
[0, 1, 4, 9, 16]
0

The array was created inside squares, whose frame on the call stack disappears when the method returns. The array survives because the return passes its reference to the caller, which stores it in firstFive. Something can still reach it. The last line shows that an array of length 0 is legal: squares(0).length is 0.

String[] args at last

In lesson 1 you were told that String[] args is a list of pieces of text, the words typed after the class name. You can now say what it is exactly: an array of String. The JVM builds it from the words you type after the class name when you run the program, and passes it to main as the argument, in the same way that doubleAll(scores) was passed an array.

code/m07-arrays-and-lists/ShowArgs.java
public class ShowArgs {
    public static void main(String[] args) {
        System.out.println("count: " + args.length);
        for (int i = 0; i < args.length; i++) {
            System.out.println(i + ": [" + args[i] + "]");
        }
    }
}
Terminal, in code/m07-arrays-and-lists
> javac ShowArgs.java
> java ShowArgs
count: 0
> java ShowArgs red blue
count: 2
0: [red]
1: [blue]
> java ShowArgs "New York" 42
count: 2
0: [New York]
1: [42]

The last point is the one that bites. Adding two arguments with + joins them as text:

code/m07-arrays-and-lists/Glue.java
public class Glue {
    public static void main(String[] args) {
        System.out.println(args[0] + args[1]);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac Glue.java
> java Glue 4 5
45

To do arithmetic you convert with Integer.parseInt from lesson 6. A program that needs input should also check that it was given enough, and say what it wanted if not. That message is called a usage message, and by convention it shows the command with placeholders in angle brackets.

code/m07-arrays-and-lists/Add.java
public class Add {
    public static void main(String[] args) {
        if (args.length != 2) {
            System.out.println("Usage: java Add <whole number> <whole number>");
            return;
        }
        int first = Integer.parseInt(args[0]);
        int second = Integer.parseInt(args[1]);
        System.out.println(first + " + " + second + " = " + (first + second));
    }
}
Terminal, in code/m07-arrays-and-lists
> javac Add.java
> java Add
Usage: java Add <whole number> <whole number>
> java Add 4 5
4 + 5 = 9
> java Add 4 5 6
Usage: java Add <whole number> <whole number>
> java Add 4 five
Exception in thread "main" java.lang.NumberFormatException: For input string: "five"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:529)
	at java.base/java.lang.Integer.parseInt(Integer.java:626)
	at Add.main(Add.java:8)

The check args.length != 2 runs before anything touches args[0]. The statement return; with no value ends the method at once. In a void method such as main, that ends the program. The program rejected zero arguments and three, accepted two, and stopped with a NumberFormatException on five, as lesson 6 showed. (You will learn to handle that failure gracefully in lesson 17.)

Without the length check, a missing argument crashes the program with an error you already know how to read:

code/m07-arrays-and-lists/NoCheck.java
public class NoCheck {
    public static void main(String[] args) {
        System.out.println("Hello, " + args[0]);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac NoCheck.java
> java NoCheck
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
	at NoCheck.main(NoCheck.java:3)
> java NoCheck Ada
Hello, Ada

Arguments are typed in the terminal, after the class name. VS Code's Run link supplies none, which is one more reason this course runs everything from the terminal.

code/m07-arrays-and-lists/star/ShowStar.java
public class ShowStar {
    public static void main(String[] args) {
        System.out.println("count: " + args.length);
        for (String arg : args) {
            System.out.println("[" + arg + "]");
        }
    }
}
Terminal, in code/m07-arrays-and-lists/star
> javac ShowStar.java Notes.java
> java ShowStar "*.java"
count: 2
[Notes.java]
[ShowStar.java]

One last detail. The name args is only a convention, because a parameter name is chosen by you, as in any method. Here the parameter is called words:

code/m07-arrays-and-lists/OtherName.java
public class OtherName {
    public static void main(String[] words) {
        System.out.println(words.length + " words were typed");
    }
}
Terminal, in code/m07-arrays-and-lists
> javac OtherName.java
> java OtherName a b c
3 words were typed

Now every part of the line you have typed since lesson 1 has a meaning. Here it is one last time, with what each word does. (As lesson 1 noted, Java 25 and later also accept shorter forms of main; this table describes the standard form.)

WordWhat it does
publicIn the standard form, lets the JVM, which is outside your class, call the method. (Lesson 9.)
staticIn the standard form, makes the method belong to the class, so the JVM needs no object to call it, as with the other methods you have written so far. (Lessons 8 and 11.)
voidThe method returns nothing.
mainThe name the JVM looks for to start the program.
String[]The type of the parameter: an array of String.
argsThe parameter's name: the words typed after the class name, one per element.

Varargs: any number of arguments

A method such as total(int[] values) forces every caller to build an array first. Java lets a method accept any number of arguments of one type with a varargs parameter, written with three dots after the type.

code/m07-arrays-and-lists/VarargsDemo.java
public class VarargsDemo {
    static int total(int... values) {
        int sum = 0;
        for (int value : values) {
            sum += value;
        }
        return sum;
    }

    static void report(String label, int... values) {
        System.out.println(label + ": " + values.length + " values, total " + total(values));
    }

    public static void main(String[] args) {
        System.out.println(total());
        System.out.println(total(5));
        System.out.println(total(1, 2, 3));
        System.out.println(total(new int[] {4, 5, 6, 7}));
        report("none");
        report("three", 10, 20, 30);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac VarargsDemo.java
> java VarargsDemo
0
5
6
22
none: 0 values, total 0
three: 3 values, total 60
code/m07-arrays-and-lists/broken/VarargsNotLast.java
public class VarargsNotLast {
    static int total(int... values, String label) {
        return values.length;
    }

    public static void main(String[] args) {
        System.out.println(total(1, 2, 3, "sum"));
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac VarargsNotLast.java
VarargsNotLast.java:2: error: varargs parameter must be the last parameter
    static int total(int... values, String label) {
                            ^
1 error

You have been calling a varargs method since lesson 6: printf takes a format string followed by any number of values, because it is itself declared with a varargs parameter. Varargs is a convenience for the caller and nothing more: the method receives an array either way. Reach for it when callers will usually have a few separate values in hand. Use a plain array parameter when they already have an array, or a collection built up as the program runs.

Arrays of arrays

The elements of an array can be anything, including other arrays. The result is a table: a two-dimensional array, written with two pairs of brackets. This section is short because the idea is just the one you already have, applied twice. Tables come back when the course builds a game on a grid.

code/m07-arrays-and-lists/Grid.java (lines 5 to 20)
int[][] table = new int[3][4];
for (int row = 0; row < table.length; row++) {
    for (int col = 0; col < table[row].length; col++) {
        table[row][col] = (row + 1) * (col + 1);
    }
}

for (int row = 0; row < table.length; row++) {
    System.out.println(Arrays.toString(table[row]));
}
System.out.println("rows: " + table.length);
System.out.println("columns: " + table[0].length);
System.out.println(Arrays.deepToString(table));

int[][] small = {{1, 2, 3}, {4, 5, 6}};
System.out.println(small[1][2]);
Terminal, in code/m07-arrays-and-lists
> javac Grid.java
> java Grid
[1, 2, 3, 4]
[2, 4, 6, 8]
[3, 6, 9, 12]
rows: 3
columns: 4
[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12]]
6

new int[3][4] makes a table of 3 rows and 4 columns, and table[1][2] means row 1, then column 2: the row index always comes first. The nested loops from lesson 4 visit every cell. The outer loop counts rows, and the inner loop counts columns within the current row, so table.length is the number of rows and table[row].length is the length of one row. Arrays.deepToString prints a table by looking inside the rows as well.

table outer array: 3 rows 0 1 2 3 1234 2468 36912 table[0] table[1] table[2] table[1][2] is 6: take row 1, then element 2 of that row.

The diagram shows what an array of arrays means: the outer array holds three references, and each reference leads to a separate row. Because a row is an object like any other, a for-each loop over the table hands you whole rows, and rows may even have different lengths:

code/m07-arrays-and-lists/Rows.java (lines 3 to 6)
int[][] rows = {{1}, {2, 3}, {4, 5, 6}};
for (int[] row : rows) {
    System.out.println(row.length);
}
Terminal, in code/m07-arrays-and-lists
> javac Rows.java
> java Rows
1
2
3

The three lines are the lengths of the three rows: 1, 2 and 3.

ArrayList: a list that grows

An array's length is fixed when it is created. That is awkward when you do not know the size in advance: the names typed into a program, the items in a basket. The library offers ArrayList, a list that grows and shrinks as you add and remove elements. It is another class from java.util, so it needs an import.

code/m07-arrays-and-lists/ListBasics.java
import java.util.ArrayList;

public class ListBasics {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        System.out.println(names.size());

        names.add("Ada");
        names.add("Grace");
        names.add("Linus");
        System.out.println(names.size());
        System.out.println(names.get(1));
        System.out.println(names);

        for (String name : names) {
            System.out.println("Hello, " + name);
        }
    }
}
Terminal, in code/m07-arrays-and-lists
> javac ListBasics.java
> java ListBasics
0
3
Grace
[Ada, Grace, Linus]
Hello, Ada
Hello, Grace
Hello, Linus

The declaration ArrayList<String> names = new ArrayList<>(); reads names is a list of String. The part in angle brackets says what the list holds. Lesson 19 explains what the angle brackets are and how they work; for now, just copy the pattern. On the right-hand side the empty brackets <> tell Java to use the same element type as the left. The list starts empty, with size 0.

The methods you will use all the time:

CallWhat it does
list.add(x)Puts x at the end.
list.add(i, x)Inserts x at position i, moving later elements one place along.
list.get(i)Returns the element at position i.
list.set(i, x)Replaces the element at position i.
list.remove(i)Removes the element at position i and returns it.
list.remove(x)Removes the first element equal to x and returns true, or returns false if there is none.
list.size()The number of elements.
list.contains(x)true if some element is equal to x.
list.indexOf(x)The position of the first element equal to x, or -1.
list.isEmpty()true when the size is 0.
list.clear()Removes everything.

Positions work as in an array: they start at 0, and the elements stay in the order you put them in. Here are the changing methods at work:

code/m07-arrays-and-lists/ListChange.java (lines 5 to 29)
ArrayList<String> items = new ArrayList<>();
items.add("pen");
items.add("book");
items.add("lamp");
System.out.println(items);

items.add(1, "cup");
System.out.println("after add(1, \"cup\"):  " + items);

items.set(0, "pencil");
System.out.println("after set(0, ...):    " + items);

String removed = items.remove(2);
System.out.println("remove(2) gave back " + removed + ": " + items);

boolean found = items.remove("lamp");
System.out.println("remove(\"lamp\") gave back " + found + ": " + items);

boolean missing = items.remove("sofa");
System.out.println("remove(\"sofa\") gave back " + missing + ": " + items);

items.add("cup");
System.out.println("with a second cup:    " + items);
items.remove("cup");
System.out.println("after remove(\"cup\"):  " + items);
Terminal, in code/m07-arrays-and-lists
> javac ListChange.java
> java ListChange
[pen, book, lamp]
after add(1, "cup"):  [pen, cup, book, lamp]
after set(0, ...):    [pencil, cup, book, lamp]
remove(2) gave back book: [pencil, cup, lamp]
remove("lamp") gave back true: [pencil, cup]
remove("sofa") gave back false: [pencil, cup]
with a second cup:    [pencil, cup, cup]
after remove("cup"):  [pencil, cup]

The two remove calls are different methods that happen to share a name, and the argument decides which one runs. remove(2) has an int argument, so it means the element at position 2 and hands that element back. remove("lamp") has a String argument, so it means the element equal to this and says whether it found one. With the second "cup" in the list, remove("cup") removed only one of them. Remember this pair of methods: it matters again in Lists of numbers: wrapper types.

And the questions you can ask a list:

code/m07-arrays-and-lists/ListQuery.java (lines 5 to 24)
ArrayList<String> items = new ArrayList<>();
items.add("pencil");
items.add("cup");
items.add("lamp");

System.out.println(items.contains("cup"));
System.out.println(items.contains("sofa"));
System.out.println(items.indexOf("cup"));
System.out.println(items.indexOf("sofa"));
System.out.println(items.isEmpty());

String start = "cu";
String built = start + "p";
System.out.println(built == "cup");
System.out.println(items.contains(built));

items.clear();
System.out.println(items);
System.out.println(items.isEmpty());
System.out.println(items.size());
Terminal, in code/m07-arrays-and-lists
> javac ListQuery.java
> java ListQuery
true
false
1
-1
false
false
true
[]
true
0

The first five lines of output answer contains("cup") (true), contains("sofa") (false), indexOf("cup") (1), indexOf("sofa") (-1) and isEmpty() (false). The next two lines matter: built holds the text cup, assembled while the program runs, so it is a different String object from the literal "cup". The == test says false, as lesson 6 predicts, yet contains(built) says true. The list compares elements with .equals, not with ==, which is what you want. After clear() the list prints as [], is empty, and has size 0.

Three ways to ask how many

code/m07-arrays-and-lists/HowMany.java (lines 5 to 13)
String[] array = {"a", "b", "c"};
String text = "hello";
ArrayList<String> list = new ArrayList<>();
list.add("x");
list.add("y");

System.out.println("array.length:  " + array.length);
System.out.println("text.length(): " + text.length());
System.out.println("list.size():   " + list.size());
Terminal, in code/m07-arrays-and-lists
> javac HowMany.java
> java HowMany
array.length:  3
text.length(): 5
list.size():   2
ThingHow to askWhy it looks like that
arrayarray.lengtha field, so no parentheses
Stringtext.length()a method
ArrayListlist.size()a method, with a different name

Nothing connects the three except the habit of looking them up. The compiler will correct you each time you guess wrong, as the section on errors shows.

Lists are objects too

An ArrayList variable holds a reference, so everything from An array is an object and Arrays and methods applies to it. Two variables can name one list, and a method that receives a list can change it for its caller.

code/m07-arrays-and-lists/ListShared.java
import java.util.ArrayList;

public class ListShared {
    static void addTwice(ArrayList<String> list, String word) {
        list.add(word);
        list.add(word);
    }

    public static void main(String[] args) {
        ArrayList<String> words = new ArrayList<>();
        ArrayList<String> alias = words;
        addTwice(words, "hi");
        System.out.println(words);
        System.out.println(alias);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac ListShared.java
> java ListShared
[hi, hi]
[hi, hi]

Both words and alias print the same list, and addTwice changed it although it returned nothing. It was given a copy of the reference.

Asking for an element that is not there fails, as with arrays, though the exception has a different name:

code/m07-arrays-and-lists/ListRange.java
import java.util.ArrayList;

public class ListRange {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Ada");
        names.add("Grace");
        names.add("Linus");
        System.out.println(names.get(3));
    }
}
Terminal, in code/m07-arrays-and-lists
> javac ListRange.java
> java ListRange
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
	at java.base/java.util.Objects.checkIndex(Objects.java:365)
	at java.base/java.util.ArrayList.get(ArrayList.java:428)
	at ListRange.main(ListRange.java:9)

The first line is the same kind of message as for arrays: index 3 asked for, length 3. As in lesson 6 and the Add example, the trace has several lines starting at java.base/ before your own. Those are frames inside the library, where the check happens. Read down to the first line that names your class: that one, ListRange.main(ListRange.java:9), is where your code made the bad call.

Lists of numbers: wrapper types

You might expect a list of whole numbers to be ArrayList<int>. It is not allowed:

code/m07-arrays-and-lists/broken/ListOfInt.java
import java.util.ArrayList;

public class ListOfInt {
    public static void main(String[] args) {
        ArrayList<int> numbers = new ArrayList<>();
        numbers.add(5);
        System.out.println(numbers);
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac ListOfInt.java
ListOfInt.java:5: error: unexpected type
        ArrayList<int> numbers = new ArrayList<>();
                  ^
  required: reference
  found:    int
1 error

The message says that a reference type was required and a primitive found. A list can hold only objects, and int, double, boolean, char and the other primitive types are not objects. For each primitive type the library supplies a wrapper class: an object type that holds one value of that primitive.

PrimitiveWrapper
intInteger
doubleDouble
booleanBoolean
charCharacter
longLong

The remaining primitive types, byte, short and float, have wrappers too, Byte, Short and Float.

You have already used three of them. Integer.parseInt and Double.parseDouble are methods of the wrapper classes, and the Character helpers from lesson 6 belong to the wrapper for char. That answers a question lesson 6 left open: Integer and Double are the object versions of int and double, and parsing is only one of the things they offer. Wrapper classes live in java.lang, so they need no import.

The good news is that Java converts between each primitive and its wrapper for you. Putting an int where an Integer is expected is called autoboxing, and taking the number back out is unboxing.

code/m07-arrays-and-lists/BoxingDemo.java (lines 5 to 26)
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);

int first = numbers.get(0);
System.out.println(first + 1);

int total = 0;
for (int n : numbers) {
    total += n;
}
System.out.println(total);

ArrayList<Double> prices = new ArrayList<>();
prices.add(2.5);
prices.add(4.0);
System.out.println(prices);

Integer boxed = 7;
int plain = boxed;
System.out.println(boxed + plain);
Terminal, in code/m07-arrays-and-lists
> javac BoxingDemo.java
> java BoxingDemo
11
60
[2.5, 4.0]
14

numbers.add(10) boxes the 10. int first = numbers.get(0) unboxes the element, so first + 1 is plain arithmetic and prints 11. The for-each loop declares int n and unboxes each element as it goes. The conversion is so smooth that you can forget it is happening, and three traps live in that gap. Each of them is shown running.

Trap 1: remove by position or by value?

Predict

The list holds 10, 20, 30 and 1. What does it contain after numbers.remove(1)? And after numbers.remove(Integer.valueOf(1))? (Integer.valueOf(1) turns the int 1 into an Integer object.)

code/m07-arrays-and-lists/RemoveTrap.java (lines 5 to 15)
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(1);

numbers.remove(1);
System.out.println(numbers);

numbers.remove(Integer.valueOf(1));
System.out.println(numbers);
Reveal the answer
Terminal, in code/m07-arrays-and-lists
> javac RemoveTrap.java
> java RemoveTrap
[10, 30, 1]
[10, 30]

After remove(1) the list is [10, 30, 1]: the 20 went, not the 1. The argument 1 is an int, and the version of remove that takes an int removes by position, so it took out the element at position 1. To remove by value you must pass an Integer object, which Integer.valueOf(1) supplies. Then the other version runs, finds the element equal to 1, and the list becomes [10, 30]. For an ArrayList<String> there is no ambiguity, because a String can never be mistaken for a position. The trap shows up with lists of Integer, where an int argument could mean either thing.

Trap 2: == on two wrapper objects

Two Integer variables are references to objects, so == compares references, as it did for strings and arrays. Boxing does not always create a new object, which makes this trap hard to see.

code/m07-arrays-and-lists/BoxEquals.java
public class BoxEquals {
    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;
        System.out.println("100 == 100:   " + (a == b));

        Integer c = 1000;
        Integer d = 1000;
        System.out.println("1000 == 1000: " + (c == d));
        System.out.println("equals:       " + c.equals(d));
        System.out.println("c == 1000:    " + (c == 1000));
    }
}
Terminal, in code/m07-arrays-and-lists
> javac BoxEquals.java
> java BoxEquals
100 == 100:   true
1000 == 1000: false
equals:       true
c == 1000:    true

Equal numbers, different answers. Java guarantees that boxing a value from -128 to 127 gives the same object every time, so a == b happens to be true for 100. For any other value it promises nothing, and on the computer this course was tested on 1000 boxed twice gives two different objects, so c == d is false. A JVM is allowed to share more objects than the guarantee requires, so the range where == happens to work is not something to rely on. A test that passes on small numbers and fails on large ones is the usual way this bug shows itself. Always compare wrapper objects with .equals, as you do with strings. When one side is a plain int, as in c == 1000, the Integer is unboxed and the numbers are compared, which is safe.

Trap 3: a wrapper can be null

An int always holds a number. An Integer is a reference, and a reference can be null. A method can therefore return no answer as null, which a plain int could never express:

code/m07-arrays-and-lists/broken/PrimitiveNull.java
public class PrimitiveNull {
    public static void main(String[] args) {
        int age = null;
        System.out.println(age);
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac PrimitiveNull.java
PrimitiveNull.java:3: error: incompatible types: <null> cannot be converted to int
        int age = null;
                  ^
1 error
code/m07-arrays-and-lists/NullBox.java
public class NullBox {
    static Integer lookupAge(String name) {
        if (name.equals("Ada")) {
            return 36;
        }
        return null;
    }

    static Boolean isMember(String name) {
        if (name.equals("Ada")) {
            return true;
        }
        if (name.equals("Bob")) {
            return false;
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(lookupAge("Ada"));
        System.out.println(lookupAge("Zed"));
        System.out.println(isMember("Ada"));
        System.out.println(isMember("Bob"));
        System.out.println(isMember("Zed"));

        int age = lookupAge("Zed");
        System.out.println("age is " + age);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac NullBox.java
> java NullBox
36
null
true
false
null
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "NullBox.lookupAge(String)" is null
	at NullBox.main(NullBox.java:26)

The first five lines show that lookupAge and isMember are allowed to answer null. The crash comes from int age = lookupAge("Zed"). Unboxing means calling intValue() on the object, and there is no object. The message names the call that failed (Integer.intValue()) and the reason, the return value of NullBox.lookupAge(String) is null, which points straight at the cause. The same thing happens with Boolean:

code/m07-arrays-and-lists/NullBool.java
public class NullBool {
    static Boolean isMember(String name) {
        if (name.equals("Ada")) {
            return true;
        }
        if (name.equals("Bob")) {
            return false;
        }
        return null;
    }

    public static void main(String[] args) {
        if (isMember("Ada")) {
            System.out.println("Ada is a member");
        }
        if (isMember("Zed")) {
            System.out.println("Zed is a member");
        } else {
            System.out.println("Zed is not a member");
        }
    }
}
Terminal, in code/m07-arrays-and-lists
> javac NullBool.java
> java NullBool
Ada is a member
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "NullBool.isMember(String)" is null
	at NullBool.main(NullBool.java:16)

A boolean is true or false. A Boolean can be true, false or null, and an if cannot handle the third. A boolean is not exactly the same as a Boolean. This is one real difference, and the one most likely to catch you out. Use the primitive types unless the language forces an object, which in practice means inside a list. When you do hold a wrapper, remember that it may be null, and check before you unbox.

Changing a list while looping over it

A for-each loop over a list keeps its own place in the list. If the list changes size behind its back, the loop's idea of where it is no longer matches the list. Here is a natural-looking program that removes every name starting with A:

code/m07-arrays-and-lists/ModifyInLoop.java (lines 5 to 16)
ArrayList<String> names = new ArrayList<>();
names.add("Ann");
names.add("Bob");
names.add("Alan");
names.add("Cy");

for (String name : names) {
    System.out.println("looking at " + name);
    if (name.startsWith("A")) {
        names.remove(name);
    }
}
Terminal, in code/m07-arrays-and-lists
> javac ModifyInLoop.java
> java ModifyInLoop
looking at Ann
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1104)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1058)
	at ModifyInLoop.main(ModifyInLoop.java:11)

The program looked at Ann, removed it, and then crashed with ConcurrentModificationException. Look at the line number in the trace: it is 11, the for line, and not 14, where the remove is. remove itself succeeded. The loop noticed on its next step that the list had been changed by someone other than itself, and refused to continue. Adding an element inside the loop fails in the same way:

code/m07-arrays-and-lists/AddInLoop.java (lines 5 to 11)
ArrayList<String> names = new ArrayList<>();
names.add("Ann");
names.add("Bob");

for (String name : names) {
    names.add(name + "!");
}
Terminal, in code/m07-arrays-and-lists
> javac AddInLoop.java
> java AddInLoop
Exception in thread "main" java.util.ConcurrentModificationException
	at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1104)
	at java.base/java.util.ArrayList$Itr.next(ArrayList.java:1058)
	at AddInLoop.main(AddInLoop.java:9)

It would be tempting to treat this exception as a reliable alarm. It is not.

Predict

This program removes b from the list a, b, c while looping over it. Does it throw? What does it print?

code/m07-arrays-and-lists/SilentSkip.java (lines 5 to 16)
ArrayList<String> letters = new ArrayList<>();
letters.add("a");
letters.add("b");
letters.add("c");

for (String letter : letters) {
    System.out.println("looking at " + letter);
    if (letter.equals("b")) {
        letters.remove(letter);
    }
}
System.out.println(letters);
Reveal the answer
Terminal, in code/m07-arrays-and-lists
> javac SilentSkip.java
> java SilentSkip
looking at a
looking at b
[a, c]

It does not throw. It prints looking at a, looking at b, and then [a, c]. The element c was never looked at. After the removal the list has 2 elements, and the loop, which had just finished position 1, concluded that it had reached the end. The program silently skipped an element, which is worse than a crash. The exception is thrown only when the loop happens to take another step after the change, so never remove from or add to a list inside a for-each over that list, whether or not it seems to work.

There are two safe ways to remove elements while looping.

code/m07-arrays-and-lists/SafeRemove.java (lines 5 to 28)
ArrayList<String> names = new ArrayList<>();
names.add("Ann");
names.add("Bob");
names.add("Alan");
names.add("Cy");

// Way 1: walk backwards, so removing never shifts an unvisited element
ArrayList<String> backwards = new ArrayList<>(names);
for (int i = backwards.size() - 1; i >= 0; i--) {
    if (backwards.get(i).startsWith("A")) {
        backwards.remove(i);
    }
}
System.out.println(backwards);

// Way 2: leave the original alone and collect what to keep
ArrayList<String> kept = new ArrayList<>();
for (String name : names) {
    if (!name.startsWith("A")) {
        kept.add(name);
    }
}
System.out.println(kept);
System.out.println(names);
Terminal, in code/m07-arrays-and-lists
> javac SafeRemove.java
> java SafeRemove
[Bob, Cy]
[Bob, Cy]
[Ann, Bob, Alan, Cy]

In "Way 1", new ArrayList<>(names) builds a separate list holding the same elements, so that the original names can still be printed at the end. It is explained properly in Making a list from known values.

Array or ArrayList?

ArrayArrayList
Sizefixed when createdgrows and shrinks
Element typesprimitives or objects: int[], String[]objects only: ArrayList<Integer>
Read and writea[i]list.get(i) and list.set(i, x)
How manya.lengthlist.size()
Printingneeds Arrays.toStringprints its contents directly
Needs an importno (but Arrays does)yes

Use an array when the number of elements is known and fixed, or when you want primitives without boxing, as in a table of numbers. Use an ArrayList when elements come and go. Arrays still matter even if you prefer lists, because args and varargs are arrays.

Making a list from known values

Two library methods build a list directly from values you write.

code/m07-arrays-and-lists/ListOfDemo.java
import java.util.ArrayList;
import java.util.List;

public class ListOfDemo {
    public static void main(String[] args) {
        List<String> days = List.of("Mon", "Tue", "Wed");
        System.out.println(days);
        System.out.println(days.get(1) + " " + days.size());

        ArrayList<String> growable = new ArrayList<>(days);
        growable.add("Thu");
        System.out.println(growable);

        days.add("Thu");
        System.out.println("not reached");
    }
}
Terminal, in code/m07-arrays-and-lists
> javac ListOfDemo.java
> java ListOfDemo
[Mon, Tue, Wed]
Tue 3
[Mon, Tue, Wed, Thu]
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:156)
	at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:161)
	at ListOfDemo.main(ListOfDemo.java:14)

List.of("Mon", "Tue", "Wed") builds a list of exactly those values. Its type is written List<String>, which needs import java.util.List;. List is a more general type than ArrayList: a List<String> variable can hold an ArrayList or the kind of list that List.of builds. Lesson 16 explains how one type can stand for several, and lesson 18 uses it all the time. For now, treat List<String> as a list of strings that you can read, loop over and print.

A list from List.of cannot be changed at all. days.add("Thu") failed with UnsupportedOperationException, which means this list does not support that operation, and so does set:

code/m07-arrays-and-lists/ListOfSet.java
import java.util.List;

public class ListOfSet {
    public static void main(String[] args) {
        List<String> days = List.of("Mon", "Tue");
        days.set(0, "Sun");
        System.out.println("not reached");
    }
}
Terminal, in code/m07-arrays-and-lists
> javac ListOfSet.java
> java ListOfSet
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:156)
	at java.base/java.util.ImmutableCollections$AbstractImmutableList.set(ImmutableCollections.java:278)
	at ListOfSet.main(ListOfSet.java:6)

To get a list you can change, pass it to new ArrayList<>(...). Writing new ArrayList<>(...) with a list in the parentheses builds a new ArrayList holding the same elements, as the growable line in ListOfDemo shows. The other method, Arrays.asList, is looser. It lets you replace elements, and it writes through to the array it was given, but it cannot add or remove:

code/m07-arrays-and-lists/AsListDemo.java
import java.util.Arrays;
import java.util.List;

public class AsListDemo {
    public static void main(String[] args) {
        String[] letters = {"x", "y"};
        List<String> fixed = Arrays.asList(letters);
        fixed.set(0, "z");
        System.out.println(fixed);
        System.out.println(Arrays.toString(letters));

        fixed.add("w");
        System.out.println("not reached");
    }
}
Terminal, in code/m07-arrays-and-lists
> javac AsListDemo.java
> java AsListDemo
[z, y]
[z, y]
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractList.add(AbstractList.java:155)
	at java.base/java.util.AbstractList.add(AbstractList.java:113)
	at AsListDemo.main(AsListDemo.java:12)

The set on the list changed the array letters too, since the list is a view of that array, which is why the second line reads [z, y] as well. The add failed. Removing fails in the same way:

code/m07-arrays-and-lists/AsListRemove.java
import java.util.Arrays;
import java.util.List;

public class AsListRemove {
    public static void main(String[] args) {
        List<String> fixed = Arrays.asList("x", "y");
        fixed.remove(0);
        System.out.println("not reached");
    }
}
Terminal, in code/m07-arrays-and-lists
> javac AsListRemove.java
> java AsListRemove
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractList.remove(AbstractList.java:169)
	at AsListRemove.main(AsListRemove.java:7)

Both methods are good for quick lists of known values, such as the days of the week. They are not substitutes for an ArrayList when the contents will change.

Reading the messages from this lesson

You have now met most of the messages that arrays and lists produce. Four more are common enough to see once.

code/m07-arrays-and-lists/broken/AssignInitialiser.java
public class AssignInitialiser {
    public static void main(String[] args) {
        int[] scores = new int[3];
        scores = {72, 85, 91};
        System.out.println(scores[0]);
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac AssignInitialiser.java
AssignInitialiser.java:4: error: illegal start of expression
        scores = {72, 85, 91};
                 ^
AssignInitialiser.java:4: error: not a statement
        scores = {72, 85, 91};
                  ^
AssignInitialiser.java:4: error: ';' expected
        scores = {72, 85, 91};
                    ^
3 errors

The shortcut {72, 85, 91} is allowed only where the array variable is declared. On a later line, the compiler cannot make sense of the braces and reports three errors for one mistake. This is the situation from lesson 1: read only the first, and fix it. Write scores = new int[] {72, 85, 91}; instead.

code/m07-arrays-and-lists/broken/IndexOnList.java
import java.util.ArrayList;

public class IndexOnList {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Ada");
        System.out.println(names[0]);
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac IndexOnList.java
IndexOnList.java:7: error: array required, but ArrayList<String> found
        System.out.println(names[0]);
                                ^
1 error

Square brackets work only on arrays. A list needs names.get(0). The mirror-image slip is asking a list for length:

code/m07-arrays-and-lists/broken/ListLengthField.java
import java.util.ArrayList;

public class ListLengthField {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();
        names.add("Ada");
        System.out.println(names.length);
    }
}
Terminal, in code/m07-arrays-and-lists/broken
> javac ListLengthField.java
ListLengthField.java:7: error: cannot find symbol
        System.out.println(names.length);
                                ^
  symbol:   variable length
  location: variable names of type ArrayList<String>
1 error

That is the same cannot find symbol as before, and the fix is names.size(). The last common message comes at run time, from an array of objects whose elements were never filled in:

code/m07-arrays-and-lists/NullElement.java
public class NullElement {
    public static void main(String[] args) {
        String[] names = new String[2];
        names[0] = "Ada";
        System.out.println(names[0].length());
        System.out.println(names[1].length());
    }
}
Terminal, in code/m07-arrays-and-lists
> javac NullElement.java
> java NullElement
3
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local1>[1]" is null
	at NullElement.main(NullElement.java:6)

Element 0 was set, so its length printed as 3. Element 1 is still the null that a new String[] starts with, and calling a method on null is a NullPointerException. The message says what was being called (String.length()) and on what: "<local1>[1]" means element 1 of local variable number 1. The compiler does not record the real names of local variables unless it is asked to, so the message uses a number. In main, args is local variable 0 and names is number 1. The line number tells you the rest.

MessageMeaningUsual cause
ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3array index outside 0 to length - 1<= instead of < in a loop; args[0] with no arguments
IndexOutOfBoundsException: Index 3 out of bounds for length 3the same, for a listthe same
NullPointerException: Cannot invoke ...a method was called on nullan unfilled element of an object array; an unboxed null
ConcurrentModificationExceptiona list changed during for-eachadd or remove inside the loop
UnsupportedOperationExceptiona fixed list was asked to change in a way it does not allowadd, remove or (for List.of) set on a list from List.of or Arrays.asList
cannot find symbol ... variable Arraysa library class was not importedmissing import java.util.Arrays;
unexpected type, required: referencea primitive used as a list's element typeArrayList<int>

Exercises

Each exercise has a folder in work/m07-arrays-and-lists/ in your course kit. Several give you a file with the methods already declared. Keep every header exactly as written, because for most of the exercises a hidden test program will call your methods with a range of inputs, including awkward ones, and will report each check as ok or WRONG. Compile and run from the terminal, inside the exercise folder. Open a hint only after a real attempt.

warm-up

Exercise 7.1 · Rainfall summary

Work in work/m07-arrays-and-lists/ex1-rainfall/ in your course kit

A weather station records a rainfall reading, in whole millimetres, for each day of a week. Complete the three methods in Rainfall.java. A test program will call each one.

HeaderReturns
static int lowest(int[] values)the smallest element
static int highest(int[] values)the largest element
static double average(int[] values)the mean of the elements, as a double
  • You may assume the array has at least one element.
  • Readings can be negative in this exercise (a gauge that was recalibrated), so a method must work when every element is below zero.
  • None of the methods may change the array it is given. Do not sort it.

The main method in the file calls your methods on one week of readings. Once they are right it prints this:

Output of java Rainfall when all three methods are right
lowest:  0
highest: 25
average: 10.57
Hint 1

This is the largest-so-far pattern from Looping over an array, twice. Think about what value the answer variable should start with, and what would go wrong if it started at 0.

Hint 2

For the average, a sum of ints divided by an int length gives a whole number. Convert one side to double before dividing.

To check it, run python check.py m07 ex1 in your course kit folder.

warm-up

Exercise 7.2 · Predict: names, copies and boxes

Work in work/m07-arrays-and-lists/ex2-prediction-worksheet/ in your course kit

Your folder contains Worksheet.java, a program with eleven labelled output lines that exercise aliasing, methods that change arrays, the for-each copy and two wrapper traps. It is shown below. The file predictions.md is a table to fill in.

work/m07-arrays-and-lists/ex2-prediction-worksheet/Worksheet.java
import java.util.ArrayList;
import java.util.Arrays;

public class Worksheet {
    static void bump(int[] data) {
        data[0] = data[0] + 1;
    }

    static void tryReplace(int[] data) {
        data = new int[] {9, 9, 9};
        data[1] = 5;
    }

    static int[] twice(int[] data) {
        int[] result = Arrays.copyOf(data, data.length);
        for (int i = 0; i < result.length; i++) {
            result[i] = result[i] * 2;
        }
        return result;
    }

    public static void main(String[] args) {
        // Part A: two names, or two arrays?
        int[] p = {1, 2, 3};
        int[] q = p;
        q[2] = 30;
        System.out.println("A1 " + p[2]);

        int[] r = Arrays.copyOf(p, 3);
        r[0] = 100;
        System.out.println("A2 " + p[0] + " " + r[0]);
        System.out.println("A3 " + (p == q) + " " + (p == r) + " " + Arrays.equals(p, r));

        // Part B: arrays and methods
        bump(p);
        System.out.println("B1 " + p[0] + " " + q[0]);
        tryReplace(p);
        System.out.println("B2 " + Arrays.toString(p));
        int[] t = twice(p);
        System.out.println("B3 " + Arrays.toString(p) + " " + Arrays.toString(t));

        // Part C: loops
        int[] w = {1, 2, 3};
        for (int x : w) {
            x = x * 10;
        }
        System.out.println("C1 " + Arrays.toString(w));
        for (int i = 0; i < w.length; i++) {
            w[i] = w[i] * 10;
        }
        System.out.println("C2 " + Arrays.toString(w));

        // Part D: lists and boxes
        ArrayList<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(1);
        list.remove(1);
        System.out.println("D1 " + list);
        list.remove(Integer.valueOf(1));
        System.out.println("D2 " + list);
        Integer big1 = 500;
        Integer big2 = 500;
        System.out.println("D3 " + big1.equals(big2) + " " + (big1 == big2));
    }
}
  1. Before you compile or run anything, fill in the My prediction column for all eleven labels (A1 to D3). Draw the arrays and references on paper as you go.
  2. Now compile and run, and fill in Actual.
  3. For every row where the two differ, write one or two sentences saying what your picture got wrong. A row you got right needs no explanation, but if you guessed, say so.
  4. Finish with the three-sentence summary the file asks for.

Do not edit Worksheet.java. There is no sample output here, because the output is the answer. One caution: label D3 depends on the JVM's default settings, because Java only guarantees shared Integer objects for values from -128 to 127. The expected answer is the one this course's setup gives, and it is the one you get by running the program here.

Hint 1

For each line, ask two questions. How many arrays exist at that moment? Which variables refer to which? Most predictions follow from the answers.

Hint 2

When a method receives an array, it receives a copy of a reference. Ask whether the line in the method is assigning to an element (data[0] = ...) or to the parameter itself (data = ...). The two have different effects, as the sections An array is an object and Arrays and methods showed.

To check it, run python check.py m07 ex2 in your course kit folder.

core

Exercise 7.3 · Reverse in two ways

Work in work/m07-arrays-and-lists/ex3-reverse/ in your course kit

A ticket office keeps the numbers of the people waiting in an int array. Complete both methods in Reverse.java. A test program will call them.

HeaderWhat it must do
static void reverseInPlace(int[] values)reverse the order of the elements of values itself
static int[] reversedCopy(int[] values)return a new array holding the elements in reverse order, leaving values unchanged
  • reverseInPlace must not create a second array. Swap elements of the one it was given.
  • Both must work for an empty array and for arrays of odd and even length.

Then answer the three questions in answers.md. The written answers are part of the exercise. Once both methods are right, main prints:

Output of java Reverse when both methods are right
original:       [101, 102, 103, 104, 105]
reversed copy:  [105, 104, 103, 102, 101]
after in place: [105, 104, 103, 102, 101]
Hint 1

To swap two elements you need a third variable to hold one of them for a moment. Which pairs of positions must be swapped for a length of 5? For 4? How many swaps is that in each case, and what is the formula in terms of values.length?

Hint 2

If your in-place method reverses the array and then reverses it back, you looped over the whole array instead of half of it.

To check it, run python check.py m07 ex3 in your course kit folder.

core

Exercise 7.4 · Add up the arguments

Work in work/m07-arrays-and-lists/ex4-arg-sum/ in your course kit

Write ArgSum.java (class ArgSum), a program that adds up the whole numbers typed after its name. It is run as java ArgSum 4 x 10 2.5 -3, and is checked by running it with several sets of arguments.

  • A whole number, for this exercise, is an optional single - followed by one or more digits. Nothing else counts: 2.5, x, +3, - and --5 are not whole numbers. You may assume no argument has more than nine digits.
  • Write the test as a method static boolean isWhole(String text) and call it from main.
  • Go through the arguments in order. For each one that is not a whole number, print Skipped: followed by the argument. Add up the rest.
  • Afterwards print Numbers added: and how many were added, then Total: and their sum.
  • If there are no arguments at all, print only the usage line, exactly as the sample run with no arguments shows it, and stop.
  • You have not met try and catch yet. Do not use them. Decide whether an argument is a number by looking at its characters, and call Integer.parseInt only on text you already know is safe.

Sample runs from the reference solution. The last one shows that an argument in quotes is one argument, even if it contains a space.

Terminal
> javac ArgSum.java
> java ArgSum
Usage: java ArgSum <whole number>...
> java ArgSum 4 x 10 2.5 -3
Skipped: x
Skipped: 2.5
Numbers added: 3
Total: 11
> java ArgSum - 7 --5 "12 5" +3
Skipped: -
Skipped: --5
Skipped: 12 5
Skipped: +3
Numbers added: 1
Total: 7
Hint 1

Inside isWhole, a String can be examined one character at a time with charAt, and Character.isDigit from lesson 6 tells you whether a character is a digit. Decide what to do about a leading minus before the loop, and what to do for the text - on its own.

Hint 2

Test your program from the terminal with awkward input before you ask for it to be checked: no arguments, a single -, and a negative number.

To check it, run python check.py m07 ex4 in your course kit folder.

core

Exercise 7.5 · Word tools

Work in work/m07-arrays-and-lists/ex5-word-tools/ in your course kit

Complete three methods in WordTools.java. A test program will call them.

HeaderWhat it must do
static String longest(String... words)return the longest of the words. If several are equally long, return the earliest. With no words at all, return the empty string "".
static ArrayList<String> withoutDuplicates(ArrayList<String> words)return a new list holding each distinct word once, in the order of its first appearance. The list passed in must not change. Words are equal if .equals says so, so Tea and tea are different words.
static void removeShort(ArrayList<String> words, int minLength)remove, from the list passed in, every word shorter than minLength characters, keeping the others in their original order.
  • Do not remove from a list inside a for-each loop over that same list.
  • The test program checks that removeShort changed the caller's own list and that withoutDuplicates did not.

The main method in the file shows the three methods at work. Once they are right it prints:

Output of java WordTools when all three methods are right
banana
[]
[tea, milk, jam, Tea]
[tea, milk, tea, jam, milk, Tea]
[milk, milk]
Hint 1

For longest, inside the method words is an ordinary array. For withoutDuplicates, ask the new list a question before each add.

Hint 2

For removeShort, read the section Changing a list while looping over it again. Test it on a list in which two short words sit next to each other, since that is where the wrong kind of loop gives itself away.

To check it, run python check.py m07 ex5 in your course kit folder.

stretch

Exercise 7.6 · Cinema seating

Work in work/m07-arrays-and-lists/ex6-cinema/ in your course kit

A cinema hall is a table of seats. Each seat is a char: '.' for a free seat and 'X' for a booked one. Complete four methods in Cinema.java. A test program will call them.

HeaderWhat it must do
static char[][] emptyHall(int rows, int seatsPerRow)return a new table with every seat free.
static boolean book(char[][] hall, int row, int seat)if the seat exists and is free, mark it 'X' and return true. In every other case (already booked, or a row or seat number outside the hall) change nothing and return false. It must never throw an exception.
static int[] freePerRow(char[][] hall)return an array with one element per row: the number of free seats in that row.
static int firstRowWithBlock(char[][] hall, int count)return the lowest-numbered row that has count or more free seats side by side, or -1 if no row does. You may assume count is at least 1.

Rows and seats are numbered from 0, like array indexes, so book(hall, 0, 2) means the first row and the third seat. The file also contains show and main, which are already written. They print the hall and call your methods. Once all four are right, the output is:

Output of java Cinema when all four methods are right
true
false
true
true
false
..X..
XX...
.....
[4, 3, 5]
1
2
-1

The twelve lines are, in order: the five results of book; the three rows of the hall; the free seats per row; and the answers to firstRowWithBlock for blocks of 3, 4 and 6.

Hint 1

In book, check the row number first, and only then look at the length of that row. The order of the checks decides whether it can ever throw. For emptyHall, a table made with new char[rows][seatsPerRow] starts with the default char, which is not '.'.

Hint 2

For firstRowWithBlock, walk along one row with a counter of how many free seats you have seen in a row. When does the counter go back to zero? When is the answer found?

To check it, run python check.py m07 ex6 in your course kit folder.

Summary

Words introduced in this lesson

TermMeaning
ArrayA fixed number of elements of one type, reached by index.
Element, index, lengthOne item of an array; its position, counted from 0; how many elements the array has.
Default valueWhat an element holds before you assign to it: zero, false or null.
FieldA value stored inside an object, read with a dot and no parentheses, as in array.length.
ObjectA block of memory, created while the program runs, that holds data and can be asked to do things with methods. Lesson 8 gives the full definition.
AliasA second variable that refers to the same object as the first.
For-each loopfor (Type x : collection): visits every element in order, without an index.
PackageA named group of library classes, such as java.util.
ImportA line above the class that lets you use a class by its short name.
Usage messageThe text a program prints to say how it should be run.
VarargsA final parameter, written type..., that accepts any number of arguments and arrives as an array.
Two-dimensional arrayAn array whose elements are arrays; a table indexed by row, then column.
ArrayListA list that grows and shrinks, holding objects.
Wrapper classThe object type for a primitive: Integer, Double, Boolean, Character.
Autoboxing, unboxingThe automatic conversion of a primitive to its wrapper, and back.
ConcurrentModificationExceptionThrown when a list is changed during a for-each over it.