Chapter 3 · Data
Arrays
Step 1 of 21 · Concept
An array is a row of cells
An array keeps many values of one type under one name. int[] means "array of int", and String[]
"array of String".
int[] temps = {12, 15, 9, 20, 17};
The array lives on the heap, and temps holds an arrow to it. Each value is an element, in a cell with an
index from 0, as a String's characters have.
Step 2 of 21 · Quiz
Which cell?
int[] temps = {12, 15, 9, 20, 17}; What is temps[2]?
Step 3 of 21 · Concept
Make, read and change an array
| write | means |
|---|---|
{12, 15, 9} | an array of these three values |
new int[4] | an array of 4 cells, each 0 for now |
temps[0] | the element at index 0 |
temps[2] = 10; | puts 10 in the cell at index 2 |
temps.length | how many cells: no (), unlike a String's length() |
An array cannot grow or shrink. Its length is fixed when it is made. new fills an int[] with 0, and a
String[] with null: no object yet (lesson 7).
Step 4 of 21 · Quiz
A new array
int[] squares = new int[4]; What are squares.length and squares[3]?
Step 5 of 21 · Concept
A loop visits every index
for (int i = 0; i < temps.length; i++) {
System.out.println(temps[i]);
}
The loop starts at the first index, 0. It stops when i reaches temps.length: that index does not exist. So it
works for an array of any length.
Step 6 of 21 · Demo
An array at work
Run it. Find temps[2] = 10 in the output, and the four squares made by new int[4] and a loop.
Step 7 of 21 · Concept
for-each: every element, no index
When a loop needs every element but not its index, the for-each loop is shorter:
for (int t : temps) {
System.out.println(t);
}
Read it as "for each t in temps". t holds the first element, then the next, up to the last. There is no
index, so it cannot go too far.
Step 8 of 21 · Quiz
Predict the output
What does this print?
String[] names = {"Ada", "Grace", "Alan"};
for (String name : names) {
System.out.print(name.charAt(0));
}
Step 9 of 21 · Exercise
Your turn: warm days
With one for-each loop over temps, count the days of 15 degrees or more, and find the highest temperature. The
program must print:
Warm days: 4
Highest: 22
One loop can do both jobs: each round asks two questions about the day t.
for (int t : temps) { … }. Inside: if t >= 15, add 1 to warm; if t > highest, store t in highest.
for (int t : temps) {
if (t >= 15) {
warm++;
}
if (t > highest) {
highest = t;
}
}
Step 10 of 21 · Concept
There is no cell 3
An array of length 3 has the indexes 0, 1 and 2. Asking for names[3] stops the program with an exception:
ArrayIndexOutOfBoundsException.
The usual cause is a loop that runs one round too many: i <= names.length instead of i < names.length.
Step 11 of 21 · Quiz
Which round fails?
names has 3 elements. Which round of this loop stops the program?
for (int i = 0; i <= names.length; i++) {
System.out.println(i + ": " + names[i]);
}
Step 12 of 21 · Demo
A crash on purpose
Run it. The for-each greets everyone; then the for crashes. Read the stack trace as in lesson 4: the kind of
problem, its message, then the line.
Step 13 of 21 · Try it
Try it: one round fewer
The trace points at line 8, names[i]. The mistake is in the loop's check on line 7. Fix it so the program
numbers the names without crashing.
The last index is names.length - 1. Which comparison stops before names.length?
Step 14 of 21 · Concept
Arrays go in and out of methods
A method can take an array and return one:
static int[] doubled(int[] a) { … }
To print a whole array, use Arrays.toString(numbers): it gives text such as [3, 1, 4]. It needs
import java.util.Arrays;, as Scanner needed its import in lesson 6.
Step 15 of 21 · Trace
One array, two arrows
main passes its array to addOne. Press Next and watch the arrows.
static void addOne(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] += 1;
}
}
public static void main(String[] args) {
int[] numbers = {3, 1, 4};
addOne(numbers);
System.out.println(Arrays.toString(numbers));
}numbersholds an arrow to the array 3, 1, 4. Line 9 callsaddOne.addOne's frame has a boxa. It got a copy of the arrow, not of the array.- The loop added 1 to every cell through
a.addOneis about to end. addOne's frame is gone.numberspoints at the same array, now 4, 2, 5.- Line 10 printed
[4, 2, 5], and the program is over.
Step 16 of 21 · Quiz
What will it print?
doubled makes a new array; addOne changes the one it gets. Type exactly what main prints.
int[] numbers = {3, 1, 4, 1, 5};
int[] twice = doubled(numbers);
System.out.println(Arrays.toString(twice));
System.out.println(Arrays.toString(numbers));
addOne(numbers);
System.out.println(Arrays.toString(numbers));
Step 17 of 21 · Demo
See it run
Run it and compare with your answer. doubled makes its own array with new; addOne makes none.
Step 18 of 21 · Exercise
Your turn: reverse
Complete reverse: it returns a new array with the elements of a in the opposite order. a itself stays as it
is. The program must print:
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
[8, 7]
Make a second array of the same length, as doubled does. Then fill it with a loop over its indexes.
result[0] gets the last element of a, result[1] the one before it. The last index of a is a.length - 1.
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = a[a.length - 1 - i];
}
return result;
Step 19 of 21 · Check yourself
Check yourself: test results
Write the three methods, each as its comment says. The program must print exactly:
Sum: 460
At least 80: 3
[95, 81, 90]
atLeast needs the length of its new array first: countAtLeast gives it. A second counter says which cell to
fill next.
Step 20 of 21 · Challenge · optional
Challenge: count the dice
Optional. It earns the lesson's third star.
rolls holds seven throws of a die. Count how often each face came up, with the array counts. The program must
print:
1: 1
2: 1
3: 3
4: 0
5: 0
6: 2
A roll is also an index: a roll of 3 adds 1 to the cell counts[3].
Loop over rolls with a for-each. Inside it, counts[r]++; adds 1 to the cell for the roll r.
for (int r : rolls) {
counts[r]++;
}
Step 21 of 21 · Recap
Recap
- An array is a row of cells of one type on the heap. Its box holds an arrow to it.
- Indexes run from 0 to
length - 1. One more stops the program. - A
forover the indexes or a for-each visits every element. - A method given an array gets an arrow to the same array: its changes are the caller's too.
Next: lesson 11 puts a loop inside a loop, and arrays inside an array: a grid.
Review
5 questions from this lesson, in a new order each time. Answer from memory: 3 of 5 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
public class Temps {
public static void main(String[] args) {
int[] temps = {12, 15, 9, 20, 17};
System.out.println("Days: " + temps.length);
System.out.println("First: " + temps[0]);
System.out.println("Last: " + temps[temps.length - 1]);
temps[2] = 10;
for (int i = 0; i < temps.length; i++) {
System.out.print("Day " + (i + 1));
System.out.println(": " + temps[i]);
}
int[] squares = new int[4];
for (int i = 0; i < squares.length; i++) {
squares[i] = i * i;
}
System.out.println("Last square: " + squares[3]);
}
}
public class Warm {
public static void main(String[] args) {
int[] temps = {12, 15, 9, 20, 17, 14, 22};
int warm = 0;
// the first day is the highest so far
int highest = temps[0];
// loop over temps here
System.out.println("Warm days: " + warm);
System.out.println("Highest: " + highest);
}
}
public class Names {
public static void main(String[] args) {
String[] names = {"Ada", "Grace", "Alan"};
for (String name : names) {
System.out.println("Hello, " + name);
}
for (int i = 0; i <= names.length; i++) {
System.out.println(i + ": " + names[i]);
}
}
}
public class Names {
public static void main(String[] args) {
String[] names = {"Ada", "Grace", "Alan"};
for (String name : names) {
System.out.println("Hello, " + name);
}
for (int i = 0; i <= names.length; i++) {
System.out.println(i + ": " + names[i]);
}
}
}
import java.util.Arrays;
public class Tools {
static int[] doubled(int[] a) {
int[] result = new int[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = 2 * a[i];
}
return result;
}
static void addOne(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i] += 1;
}
}
public static void main(String[] args) {
int[] numbers = {3, 1, 4, 1, 5};
int[] twice = doubled(numbers);
System.out.println(Arrays.toString(twice));
System.out.println(Arrays.toString(numbers));
addOne(numbers);
System.out.println(Arrays.toString(numbers));
}
}
import java.util.Arrays;
public class Reverse {
static int[] reverse(int[] a) {
// a new array: a's elements, last to first
return a;
}
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int[] back = reverse(numbers);
System.out.println(Arrays.toString(back));
System.out.println(Arrays.toString(numbers));
int[] pair = {7, 8};
System.out.println(Arrays.toString(reverse(pair)));
}
}
import java.util.Arrays;
public class Results {
// the total of all the scores
static int sum(int[] scores) {
return 0;
}
// how many scores are limit or more
static int countAtLeast(int[] scores, int limit) {
return 0;
}
// a new array of the scores >= limit, in order
static int[] atLeast(int[] scores, int limit) {
return scores;
}
public static void main(String[] args) {
int[] scores = {72, 95, 58, 81, 64, 90};
System.out.println("Sum: " + sum(scores));
System.out.print("At least 80: ");
System.out.println(countAtLeast(scores, 80));
int[] high = atLeast(scores, 80);
System.out.println(Arrays.toString(high));
}
}
public class Dice {
public static void main(String[] args) {
int[] rolls = {3, 6, 1, 3, 3, 6, 2};
// counts[1] to counts[6]; counts[0] stays 0
int[] counts = new int[7];
// count each roll in counts
for (int face = 1; face <= 6; face++) {
System.out.println(face + ": " + counts[face]);
}
}
}