Storing Lists of Data with Arrays
Keeping many values in one place
So far every variable you have created has held exactly one value. An array lets you store many values of the same type together, under a single name.
int[] scores = {85, 92, 78, 90};
This creates an array called scores holding four whole numbers. You can picture it as a row of numbered boxes sitting side by side.
Reading and changing array values
Each value in an array has a position, called its index, and counting starts at 0 rather than 1. That means the first item is at index 0, the second at index 1, and so on.
System.out.println(scores[0]);
System.out.println(scores[2]);
scores[1] = 100;
The first line prints 85, the first score. The second prints 78, the third score. The last line replaces the second score with 100.
Finding out how big an array is
Every array knows its own size through the length property:
System.out.println(scores.length);
That would print 4, since there are four scores stored in the array.
Looping through every item
Arrays and loops work together naturally. Instead of writing out scores[0], scores[1], scores[2], and scores[3] by hand, you can loop through the whole array:
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
This prints every score, one after another, no matter how many items the array holds.
Arrays are the first step toward managing collections of data, a skill you will use constantly once you start working with real information like lists of names, prices, or scores.
Quick check
Q1 What index does the first item in a Java array have?
Q2 Which property tells you how many items are in an array?
Want to save your progress? It's free.
Create a free account