An array stores a fixed number of values of the same type under a single variable name, which is far more manageable than declaring a separate variable for every value when there are more than just a couple.
Creating an array
int[] scores = {90, 85, 70, 60};This single array holds four related numbers together, with a size fixed at four the moment it is created.
Reading and changing values
Each item has a position, called an index, and counting always starts at zero:
int first = scores[0]; // 90
int third = scores[2]; // 70
scores[1] = 88; // change the second valueA common mistake
An array with four items has valid indexes 0 through 3; asking for scores[4] does not exist and throws an ArrayIndexOutOfBoundsException at runtime. This off-by-one mistake, forgetting that the last index is length minus one, catches nearly every beginner at least once.
Looping through an array
for (int s : scores) {
System.out.println(s);
}
System.out.println("Total items: " + scores.length);The length field, without parentheses since it is a field and not a method, always reports how many items an array holds.
Arrays of objects
Arrays are not limited to primitives; they can just as easily hold objects, such as a list of Person objects created earlier:
Person[] people = new Person[3];
people[0] = new Person("Ann", 30);Multidimensional arrays
An array of arrays models a grid or table, useful for things like a small game board or a spreadsheet-style layout:
int[][] grid = new int[3][3];
grid[1][2] = 5;Useful helpers from the Arrays class
The built-in Arrays utility class provides ready-made operations that avoid writing loops for common tasks, such as sorting or printing an array in a readable form:
Arrays.sort(scores);
System.out.println(Arrays.toString(scores));Arrays versus lists
Arrays are fast and memory-efficient but cannot grow or shrink once created. When the number of items may change over time, an ArrayList is usually a better fit, trading a small amount of overhead for the convenience of adding and removing items freely, a comparison covered in more depth in the tutorial on Java collections.