Sub topic 8
Working with Arrays
So far, each variable you have made held one value. What if you need to store ten test scores? Making ten separate variables would be painful. An array is a container that holds many values of the same type in one variable. You will learn how to create arrays, read and change their values, and loop through them.
Creating an Array
An array has a fixed size. You set the size when you create it, and it cannot change. Here are two common ways to make an array:
// Way 1: create an empty array, then fill it
int[] scores = new int[3];
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
// Way 2: create and fill the array at once
int[] ages = {10, 20, 30};The word int[] means "an array of ints". The word new asks Java to make a new array of the given size.
Indexes: Counting From Zero
Each slot in an array has a number called an index. Indexes start at 0, not 1. For an array of size 3, the indexes are 0, 1, and 2.
int[] ages = {10, 20, 30};
System.out.println(ages[0]); // prints 10
System.out.println(ages[2]); // prints 30Every array also has a length field that tells you how many slots it has:
System.out.println(ages.length); // prints 3Looping Through an Array
Arrays and loops work well together. A for loop can visit every slot using the index:
int[] scores = {85, 92, 78};
int total = 0;
for (int i = 0; i < scores.length; i++) {
total = total + scores[i];
}
System.out.println("Average: " + total / scores.length);Java also has a shorter form called the for-each loop. It gives you each value one at a time, with no index needed:
for (int s : scores) {
System.out.println(s);
}Use a regular for loop when you need the index (for example, to change a slot). Use a for-each loop when you only need to read each value.
flowchart TD
A[Start loop] --> B{Is i less than length?}
B -- yes --> C[Use scores with index i]
C --> D[Add to total]
D --> E[i becomes i + 1]
E --> B
B -- no --> F[Loop ends]caption: How a for loop visits every slot of an array. alt: A flowchart that starts a loop, checks whether the index is less than the array length, uses the value at that index, adds it to a total, increases the index, and repeats until the check fails.
A Worked Example: Find the Highest Score
public class MaxScore {
public static void main(String[] args) {
int[] scores = {85, 92, 78};
int max = scores[0]; // start with the first value
for (int i = 1; i < scores.length; i++) {
if (scores[i] > max) {
max = scores[i];
}
}
System.out.println("Highest score: " + max);
}
}We start max at the first value, then walk through the rest of the array. Whenever we find something bigger, we keep it. Compile and run this with:
javac MaxScore.java
java MaxScoreYou should see Highest score: 92.
Arrays of Other Types
Arrays can hold any one type: double[], String[], even boolean[]. All slots must hold the same type.
String[] names = {"Ana", "Bo", "Chi"};
for (String n : names) {
System.out.println("Hello, " + n);
}Exercise
Given int[] nums = {4, 8, 15};, what does nums[nums.length - 1] print?
Show answer
It prints 15. nums.length is 3, so the index is 2, which holds the last value.
Exercise
Write a for-each loop that prints every value in double[] prices = {1.5, 2.5, 3.0};.
Show answer
for (double p : prices) { System.out.println(p); }