Java · Module 4 · Lesson 11 min read

Arrays

Creating arrays

Java
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.length gives the size (it's a field, so no ()).

Default values

TypeDefault
int, long, double0 / 0.0
booleanfalse
char'\u0000'
Objects (String…)null

Reading and writing

Java
scores[0] = 90;
System.out.println(scores[0]);  // 90
scores[5] = 10;  // 💥 ArrayIndexOutOfBoundsException

Looping over arrays

Java
for (int i = 0; i < scores.length; i++) { ... }  // need the index
for (int s : scores) { ... }                       // just the values

2D arrays (grids)

Java
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 place
  • Arrays.fill(arr, -1) → fills every slot
  • Arrays.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

Java
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
    }
}