Arrays: Store and Process Multiple Values
Introduction
An array holds a fixed number of values of the same type under one name. Arrays are essential for scores, lists of IDs, and tables of data. This chapter covers one-dimensional and multi-dimensional arrays, length, traversal, and how arrays differ from collections you will meet in Collections Overview.
Prerequisites
- Variables, Loops
- Basic
if/elsefrom Conditionals
What Is an Array
An array is a container with a fixed size and indexed slots (starting at 0).
Metaphor: a row of labeled lockers—each locker has a number (index) and holds one value of the declared type.
int[] scores = {90, 85, 88};
System.out.println(scores[0]); // 90
System.out.println(scores.length); // 31) Declaring and Creating Arrays
Declaration syntax
int[] numbers; // preferred style
// int numbers[]; // legal but uncommonCreate with size (default values)
int[] counts = new int[5]; // five zeros
String[] names = new String[3]; // three null referencesCreate with initial values
int[] primes = {2, 3, 5, 7, 11};
String[] cities = {"Beijing", "Shanghai", "Guangzhou"};Once created, length is fixed. You cannot grow an array in place—use ArrayList later when you need dynamic size.
2) Accessing and Updating Elements
int[] scores = {90, 85, 88};
scores[1] = 92; // change second element
System.out.println(scores[2]); // 88
// scores[5] = 100; // ArrayIndexOutOfBoundsExceptionWarning
Valid indices are 0 through length - 1. Accessing outside that range throws ArrayIndexOutOfBoundsException.
3) Traversing Arrays
Indexed for loop
int[] scores = {90, 85, 88, 92};
for (int i = 0; i < scores.length; i++) {
System.out.println("Index " + i + ": " + scores[i]);
}Enhanced for (for-each)
for (int score : scores) {
System.out.println(score);
}Use indexed loops when you need the index; use for-each when you only need each value.
4) Common Array Operations with java.util.Arrays
Import helpers:
import java.util.Arrays;| Method | Purpose |
|---|---|
Arrays.toString(arr) | readable print |
Arrays.sort(arr) | sort ascending (in place) |
Arrays.fill(arr, value) | fill with one value |
Arrays.copyOf(arr, newLen) | copy/resize into new array |
int[] scores = {88, 95, 78, 92};
System.out.println(Arrays.toString(scores)); // [88, 95, 78, 92]
Arrays.sort(scores);
System.out.println(Arrays.toString(scores)); // [78, 88, 92, 95]Arrays.sort on int[] sorts ascending. Descending ranking patterns appear in Ranking Game.
5) Multi-Dimensional Arrays
Java supports arrays of arrays—useful for grids and tables.
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid.length); // 2 rows
System.out.println(grid[0].length); // 3 columns
System.out.println(grid[1][2]); // 6
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}Ragged arrays (rows of different lengths) are allowed but less common in beginner exercises.
6) Arrays vs Collections (Preview)
| Feature | Array | Collection (e.g. ArrayList) |
|---|---|---|
| Size | fixed at creation | can grow/shrink |
| Types | primitives or objects | objects (with wrappers for primitives) |
| Syntax | [], length | methods like add, size |
| When to start | scores, fixed tables | dynamic lists, APIs |
From chapter 34 onward, you will use lists and maps heavily. Arrays remain important for performance, algorithms, and interop with older APIs.
Real Mini Example: Class Average
public class ClassAverage {
public static void main(String[] args) {
int[] scores = {90, 85, 88, 92, 76};
int sum = 0;
for (int score : scores) {
sum += score;
}
double average = (double) sum / scores.length;
System.out.printf("Average: %.2f%n", average);
System.out.println("Highest: " + max(scores));
}
static int max(int[] values) {
int best = values[0];
for (int i = 1; i < values.length; i++) {
if (values[i] > best) {
best = values[i];
}
}
return best;
}
}Common Beginner Mistakes
Mistake 1: Assuming Length Changes
int[] data = new int[3];
// data.add(4); // arrays have no add methodMistake 2: length vs length()
Arrays use length (field). String uses length() (method).
Mistake 3: Printing an Array Directly
int[] nums = {1, 2, 3};
System.out.println(nums); // something like [I@1b6d3586
System.out.println(Arrays.toString(nums)); // [1, 2, 3]Mistake 4: Forgetting Default Values
new int[n] fills with 0; new boolean[n] with false; object arrays with null.
Mini Practice
- Create an array of five integers and print the sum
- Find the minimum value in an array
- Print a 3×3 multiplication table using a 2D array
What’s Next
Sort scores in Ranking Game, then build Guess the Number with Random.
FAQ
Can arrays store different types?
No. Each array holds one element type (int[], String[], etc.). Use objects or collections for mixed shapes later.
Why do indices start at 0?
Historical and mathematical convention in C-family languages—including Java.
Should I use arrays or ArrayList?
Use arrays when size is fixed and simple. Use ArrayList when you need to add/remove elements dynamically.
Does Arrays.sort change the original array?
Yes. It sorts in place. Copy first if you need the original order: int[] copy = Arrays.copyOf(scores, scores.length);
Can I sort descending with Arrays.sort(int[])?
Not directly for primitives. Techniques for ranking appear in the next chapter.