Arrays
An array stores many values of the same type in one variable, numbered from 0.
What you will learn
- Create and fill an array
- Read values by index
- Loop over an array
Many values, one name
A single variable holds one value. An array holds many values of the same type, all under one name. Each value sits at a numbered position called an index.
Important: indexes start at 0, not 1. So the first item is at index 0.
String[] fruits = {"apple", "banana", "cherry"};
System.out.println(fruits[0]); // first item
System.out.println(fruits[2]); // third item
System.out.println("How many: " + fruits.length);Note: Output:
apple
cherry
How many: 3
fruits[0] is apple (index 0), fruits[2] is cherry (index 2). fruits.length tells you how many items there are — note it is .length with no brackets.
Looping over an array
Arrays and loops are best friends. A for-each loop visits every item without you tracking the index:
int[] scores = {80, 95, 60, 100};
int total = 0;
for (int s : scores) {
total = total + s;
}
System.out.println("Sum of scores: " + total);
System.out.println("Average: " + (total / scores.length));Note: Output:
Sum of scores: 335
Average: 83
The for-each loop reads for (int s : scores) as for each score s in scores. We added them to 335, then divided by 4 items to get the average (integer division, so 83).
Looping with the index
The for-each loop is tidy, but sometimes you need to know which position you are at — to number items, or to change a value. For that, use a normal for loop that counts from 0 up to length - 1:
String[] fruits = {"apple", "banana", "cherry"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(i + ": " + fruits[i]);
}Note: Output:
0: apple
1: banana
2: cherry
Here i is the index, going 0, 1, 2. We stop at i < fruits.length (which is 3) so the last round uses index 2 — the final valid position. Use this style when the position matters; use for-each when it does not.
Watch out: Going out of bounds crashes the program. An array of length 3 has indexes 0, 1, 2 only. Asking for fruits[3] throws an ArrayIndexOutOfBoundsException. The last valid index is always length - 1. This is why the loop condition is i < length (not i <= length).
Tip: To make an empty array of a fixed size, write int[] nums = new int[5];. It starts filled with zeros (or empty text for a String array), ready for you to fill with a loop.
Q. In the array {"red", "green", "blue"}, what is at index 1?
✍️ Practice
- Create an int array of five numbers and print the first and last using
[0]and[length - 1]. - Use a for-each loop to print every item of a String array on its own line.
🏠 Homework
- Make an array of test scores, then loop through it to find and print the highest score.