Arrays
Creating arrays
int[] scores = new int[5]; // 5 slots, all 0
String[] names = {"Ana", "Ben"}; // filled right away
- Arrays have a fixed size that can't change after creation.
- Indexes start at 0. The last index is
length - 1. scores.lengthgives the size (it's a field, so no()).
Default values
| Type | Default |
|---|---|
int, long, double | 0 / 0.0 |
boolean | false |
char | '\u0000' |
Objects (String…) | null |
Reading and writing
scores[0] = 90;
System.out.println(scores[0]); // 90
scores[5] = 10; // 💥 ArrayIndexOutOfBoundsException
Looping over arrays
for (int i = 0; i < scores.length; i++) { ... } // need the index
for (int s : scores) { ... } // just the values
2D arrays (grids)
int[][] board = new int[3][3];
board[1][2] = 7; // row 1, column 2
The Arrays helper class
Arrays.toString(arr)→"[1, 2, 3]"(printing an array directly shows a weird address)Arrays.sort(arr)→ sorts in placeArrays.fill(arr, -1)→ fills every slotArrays.binarySearch(arr, key)→ fast search, but the array must be sorted
💡 Need a list that can grow? You'll meet ArrayList in Unit 8.
Example
import java.util.Arrays;
public class ScoreBoard {
public static void main(String[] args) {
int[] scores = {72, 95, 58, 88};
int max = scores[0];
int sum = 0;
for (int s : scores) {
sum += s;
if (s > max) max = s;
}
Arrays.sort(scores);
System.out.println(Arrays.toString(scores)); // [58, 72, 88, 95]
System.out.println("Max: " + max); // Max: 95
System.out.println("Avg: " + sum / (double) scores.length); // Avg: 78.25
}
}