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
forand 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.copyOfandArrays.sort, and say what animportline 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
. intscores 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.
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]);
}
}> javac ArrayBasics.java > java ArrayBasics first: 72 third: 0 length: 5 second now: 90
Three facts are visible here.
- Indexes start at 0. The index says how far the element is from the start, so the first element is
scores[0]and an array of length 5 has indexes 0, 1, 2, 3 and 4. In a non-empty array the last index islength - 1; an empty array has no valid index at all. - An element is an ordinary variable.
scores[1] = scores[1] + 5;reads one and writes it back, exactly as it would with a plainint. - Elements you never set are not empty.
scores[2]printed0. A new array is filled with a default value, which depends on the element type.
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]);> javac DefaultValues.java > java DefaultValues 0 0.0 false 0 null
| Element type | Default | Seen above |
|---|---|---|
numeric types (int, double, long and so on) | zero | 0 and 0.0 |
boolean | false | false |
char | the character whose code is 0, which has no visible form | casting it to int printed 0 |
objects such as String | null, meaning no object yet | null |
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.
What does this program print?
String[] words = new String[3];
words[1] = "hi";
System.out.println(words.length + " " + words[0] + " " + words[1]);Reveal the answer
> 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.
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);> 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.
public class LengthParens {
public static void main(String[] args) {
int[] scores = {72, 85, 91};
System.out.println(scores.length());
}
}> 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 errorpublic class StringLengthField {
public static void main(String[] args) {
String word = "elephant";
System.out.println(word.length);
}
}> 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 errorBoth 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.
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");
}
}> 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:
int[] scores = {72, 85, 91};
int position = -1;
System.out.println(scores[position]);> 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.
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]);> javac Alias.java > java Alias x = 5, y = 6 a[0] = 99, b[0] = 99
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.
Work out each variable's contents with a diagram before you answer. What does this print?
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
> 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.
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);
}> 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
. On every pass the variable colour in colourscolour 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:
- It cannot tell you the position. If you need to print
0: redor to compare an element with its neighbour, use the indexed loop. - It cannot replace elements. The loop variable is a new variable that starts as a copy of the element. Assigning to it changes the copy.
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?
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
> 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.
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);
}
}> javac Patterns.java > java Patterns sum 471, average 78.5 largest 91 scores of 75 or more: 4 first 85 is at position 1
- Accumulating.
sumstarts at 0 and each score is added to it. The average divides byscores.length. The(double)cast matters: without it,sum / scores.lengthwould be integer division, as in lesson 2. - Largest so far. Start from the first element,
scores[0], and replace it whenever a bigger one turns up. This needs at least one element:scores[0]on an empty array is an out-of-bounds access. - Counting.
passesgoes up by one for each element that meets the condition. - Searching. The loop looks for the first position holding the target and stops with
break. The value-1is a convention fornot found
: it can never be a real index, so it cannot be confused with an answer. The target 85 appears twice, and the search reports position 1, the earlier one, because of thebreak.
The library's array helpers, and your first import
What happens if you print an array directly?
int[] scores = {72, 85, 91};
String[] colours = {"red", "green"};
System.out.println(scores);
System.out.println(colours);> 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
and int[Ljava.lang.String; for array of
. The text after the String@ 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.
public class CharPrint {
public static void main(String[] args) {
char[] letters = {'h', 'i'};
System.out.println(letters);
}
}> 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:
public class NoImport {
public static void main(String[] args) {
int[] scores = {72, 85, 91};
System.out.println(Arrays.toString(scores));
}
}> javac NoImport.java
NoImport.java:4: error: cannot find symbol
System.out.println(Arrays.toString(scores));
^
symbol: variable Arrays
location: class NoImport
1 errorIt 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:
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:
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
:
import java.util.*;
public class WildcardImport {
public static void main(String[] args) {
int[] scores = {72, 85, 91};
System.out.println(Arrays.toString(scores));
}
}> 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
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));> 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.
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);> 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.
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));> 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.
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));> 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:
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]);
}
}> javac SortReturn.java
SortReturn.java:6: error: incompatible types: void cannot be converted to int[]
int[] sorted = Arrays.sort(scores);
^
1 errorvoid 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.
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));
}
}> 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.
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.
This method assigns a brand-new array to its parameter. What does main print after the call?
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
> 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.
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);
}
}> 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.
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] + "]");
}
}
}> 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]
- Words are separated by spaces.
red blueis two arguments,args[0]andargs[1]. - Quotes group words. To pass an argument that contains a space, put it in double quotes. In the third run,
"New York" 42is two arguments, not three. The quotes are for the terminal and are removed before the program sees the text, soargs[0]isNew York. - With nothing typed, the array is empty.
argsis not missing: it is an array of length 0. - Every argument is a
String.42arrives as the text42, not as a number.
The last point is the one that bites. Adding two arguments with + joins them as text:
public class Glue {
public static void main(String[] args) {
System.out.println(args[0] + args[1]);
}
}> 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.
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));
}
}> 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:
public class NoCheck {
public static void main(String[] args) {
System.out.println("Hello, " + args[0]);
}
}> 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.
public class ShowStar {
public static void main(String[] args) {
System.out.println("count: " + args.length);
for (String arg : args) {
System.out.println("[" + arg + "]");
}
}
}> 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:
public class OtherName {
public static void main(String[] words) {
System.out.println(words.length + " words were typed");
}
}> 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.)
| Word | What it does |
|---|---|
public | In the standard form, lets the JVM, which is outside your class, call the method. (Lesson 9.) |
static | In 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.) |
void | The method returns nothing. |
main | The name the JVM looks for to start the program. |
String[] | The type of the parameter: an array of String. |
args | The 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.
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);
}
}> javac VarargsDemo.java > java VarargsDemo 0 5 6 22 none: 0 values, total 0 three: 3 values, total 60
- Inside the method,
valuesis an ordinaryint[]. It has alengthand works in a for-each loop. - The caller may pass any number of values, including none:
total()gives an empty array and the loop does not run.total(5)andtotal(1, 2, 3)work too. - The caller may also pass an array.
total(new int[] {4, 5, 6, 7})hands the array over as it is, and the result is 22. That is howreportpasses its ownvalueson tototal. - A varargs parameter must be the last one. Java gathers whatever is left over into the array, so there can be other parameters before it, as with
String labelinreport, but nothing after. It follows that a method has at most one.
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"));
}
}> javac VarargsNotLast.java
VarargsNotLast.java:2: error: varargs parameter must be the last parameter
static int total(int... values, String label) {
^
1 errorYou 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.
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]);> 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.
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:
int[][] rows = {{1}, {2, 3}, {4, 5, 6}};
for (int[] row : rows) {
System.out.println(row.length);
}> 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.
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);
}
}
}> 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
. 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 String<> 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:
| Call | What 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:
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);> 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:
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());> 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
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());> javac HowMany.java > java HowMany array.length: 3 text.length(): 5 list.size(): 2
| Thing | How to ask | Why it looks like that |
|---|---|---|
| array | array.length | a field, so no parentheses |
String | text.length() | a method |
ArrayList | list.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.
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);
}
}> 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:
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));
}
}> 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:
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);
}
}> javac ListOfInt.java
ListOfInt.java:5: error: unexpected type
ArrayList<int> numbers = new ArrayList<>();
^
required: reference
found: int
1 errorThe 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.
| Primitive | Wrapper |
|---|---|
int | Integer |
double | Double |
boolean | Boolean |
char | Character |
long | Long |
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.
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);> 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?
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.)
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
> 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.
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));
}
}> 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:
public class PrimitiveNull {
public static void main(String[] args) {
int age = null;
System.out.println(age);
}
}> javac PrimitiveNull.java
PrimitiveNull.java:3: error: incompatible types: <null> cannot be converted to int
int age = null;
^
1 errorpublic 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);
}
}> 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
, which points straight at the cause. The same thing happens with NullBox.lookupAge(String) is nullBoolean:
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");
}
}
}> 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
:
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);
}
}> 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:
ArrayList<String> names = new ArrayList<>();
names.add("Ann");
names.add("Bob");
for (String name : names) {
names.add(name + "!");
}> 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.
This program removes b from the list a, b, c while looping over it. Does it throw? What does it print?
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
> 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.
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);> 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.
- Way 1: an indexed loop that runs backwards. When you remove position
i, every later element slides one place to the left. Going backwards, the elements that slide are ones you have already examined, so none is skipped and every index you still have to visit stays valid. A forward loop would step over the element that slides into positioni. - Way 2: build a second list. Loop over the original, which you do not change, and add the elements to keep to a new list. The last line of output shows the original still has all four names. This is also the right choice when the original must stay intact.
Array or ArrayList?
| Array | ArrayList | |
|---|---|---|
| Size | fixed when created | grows and shrinks |
| Element types | primitives or objects: int[], String[] | objects only: ArrayList<Integer> |
| Read and write | a[i] | list.get(i) and list.set(i, x) |
| How many | a.length | list.size() |
| Printing | needs Arrays.toString | prints its contents directly |
| Needs an import | no (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.
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");
}
}> 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:
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");
}
}> 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:
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");
}
}> 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:
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");
}
}> 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.
public class AssignInitialiser {
public static void main(String[] args) {
int[] scores = new int[3];
scores = {72, 85, 91};
System.out.println(scores[0]);
}
}> 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 errorsThe 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.
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]);
}
}> javac IndexOnList.java
IndexOnList.java:7: error: array required, but ArrayList<String> found
System.out.println(names[0]);
^
1 errorSquare brackets work only on arrays. A list needs names.get(0). The mirror-image slip is asking a list for length:
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);
}
}> 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 errorThat 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:
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());
}
}> 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.
| Message | Meaning | Usual cause |
|---|---|---|
ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 | array index outside 0 to length - 1 | <= instead of < in a loop; args[0] with no arguments |
IndexOutOfBoundsException: Index 3 out of bounds for length 3 | the same, for a list | the same |
NullPointerException: Cannot invoke ... | a method was called on null | an unfilled element of an object array; an unboxed null |
ConcurrentModificationException | a list changed during for-each | add or remove inside the loop |
UnsupportedOperationException | a fixed list was asked to change in a way it does not allow | add, remove or (for List.of) set on a list from List.of or Arrays.asList |
cannot find symbol ... variable Arrays | a library class was not imported | missing import java.util.Arrays; |
unexpected type, required: reference | a primitive used as a list's element type | ArrayList<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.
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.
| Header | Returns |
|---|---|
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:
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.
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.
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));
}
}- 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.
- Now compile and run, and fill in Actual.
- 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.
- 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.
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.
| Header | What 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 |
reverseInPlacemust 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:
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.
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--5are 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 frommain. - 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, thenTotal: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
tryandcatchyet. Do not use them. Decide whether an argument is a number by looking at its characters, and callInteger.parseIntonly 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.
> 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.
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.
| Header | What 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
removeShortchanged the caller's own list and thatwithoutDuplicatesdid not.
The main method in the file shows the three methods at work. Once they are right it prints:
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.
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.
| Header | What 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:
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
- An array holds a fixed number of elements of one type. Indexes run from 0 to
length - 1. A new array holds default values: zero,falseornull. Going past either end throwsArrayIndexOutOfBoundsException. - An array is an object. A variable of array type holds a reference. Assigning one array variable to another, or passing an array to a method, copies the reference and not the array, so both names reach the same array. A method can change the contents of an array it receives but cannot change which array the caller's variable refers to.
- Use an indexed loop when you need the position or want to write to the array. Use for-each when you only read. The for-each variable is a copy of the element.
- Library classes outside
java.langneed animportline, or their full name written out.Arrays.toString,Arrays.equals,Arrays.copyOfandArrays.sortdo whatprintlnand==cannot do for arrays. String[] argsis an array of the words typed after the class name. Every word is text. Checkargs.length, convert withInteger.parseInt, and print a usage message when the input is missing.- A varargs parameter,
int... values, accepts any number of arguments, including none. Inside the method it is an array. It must be the last parameter. - A table is an array of arrays:
table[row][column]. - An
ArrayList<String>is a list ofStringthat grows and shrinks. It is asked its size withsize(), and it holds objects only, so numbers go in asInteger,Doubleand so on. - Wrapper traps:
remove(int)removes by position, so remove anIntegerby value withInteger.valueOf; compare wrapper objects with.equals, not==; a wrapper can benulland unboxingnullthrowsNullPointerException. - Never add to or remove from a list inside a for-each over it. Loop backwards by index, or build a second list.
- Arrays are for a fixed size and primitives.
ArrayListis for a changing size.List.of(unchangeable) andArrays.asList(no adding or removing) make quick lists from known values.
Words introduced in this lesson
| Term | Meaning |
|---|---|
| Array | A fixed number of elements of one type, reached by index. |
| Element, index, length | One item of an array; its position, counted from 0; how many elements the array has. |
| Default value | What an element holds before you assign to it: zero, false or null. |
| Field | A value stored inside an object, read with a dot and no parentheses, as in array.length. |
| Object | A 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. |
| Alias | A second variable that refers to the same object as the first. |
| For-each loop | for (Type x : collection): visits every element in order, without an index. |
| Package | A named group of library classes, such as java.util. |
| Import | A line above the class that lets you use a class by its short name. |
| Usage message | The text a program prints to say how it should be run. |
| Varargs | A final parameter, written type..., that accepts any number of arguments and arrives as an array. |
| Two-dimensional array | An array whose elements are arrays; a table indexed by row, then column. |
ArrayList | A list that grows and shrinks, holding objects. |
| Wrapper class | The object type for a primitive: Integer, Double, Boolean, Character. |
| Autoboxing, unboxing | The automatic conversion of a primitive to its wrapper, and back. |
ConcurrentModificationException | Thrown when a list is changed during a for-each over it. |