Arrays

Reviewed & published by Brayan K

So far, each variable holds one value. But what if you need to store 100 student scores, 365 daily temperatures, or 1,000 product prices? You can't create 1,000 separate variables! Arrays solve this — they let you store multiple values of the same type in a single variable.

Part of the free Java course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.

What You'll Learn

💡 Real-World Analogy

Think of an array as a row of numbered mailboxes in an apartment building. Each mailbox (index) holds exactly one item. You access mailbox #3 directly — you don't need to check mailboxes 0, 1, and 2 first. The building has a fixed number of mailboxes decided at construction — you can't add more later.

1️⃣ Creating Arrays — Two Approaches

There are two main ways to create an array. Use the first when you already know the values. Use the second when you know the size but will fill it later.

// Approach 1: Declare with known values
int[] scores = {85, 92, 78, 95, 88};
String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri"};

// Approach 2: Declare with size (values default to 0, null, or false)
int[] temperatures = new int[7];     // 7 slots, all start at 0
String[] names = new String[100];    // 100 slots, all start at null
boolean[] flags = new boolean[5];    // 5 slots, all start at false

🔑 Key point: Once created, the array size is fixed forever. You cannot add or remove slots. If you need a resizable collection, use ArrayList (you'll learn this in the Collections lesson).

2️⃣ Accessing Elements — 0-Based Indexing

Every element in an array has an index (position number). Java uses 0-based indexing, which means the first element is at index 0, not 1. This trips up almost every beginner, so let's be clear:

int[] scores = {85, 92, 78, 95, 88};
//               [0]  [1]  [2]  [3]  [4]  ← indices

scores[0]   // 85  (first element)
scores[2]   // 78  (third element)
scores[4]   // 88  (last element)

scores.length    // 5 (number of elements — NOT an index!)
scores[scores.length - 1]  // 88 (last element — ALWAYS use this pattern)

// Modify an element
scores[2] = 82;  // Change 78 to 82

// ❌ CRASH: ArrayIndexOutOfBoundsException!
scores[5]   // Index 5 doesn't exist in a 5-element array!
scores[-1]  // Negative indices don't work in Java

⚠️ The most common array error: ArrayIndexOutOfBoundsException. This happens when you try to access an index that doesn't exist. Remember: a 5-element array has indices 0 through 4, NOT 1 through 5.

3️⃣ Looping Through Arrays

The real power of arrays comes from processing every element with a loop. There are two main approaches:

Standard For — when you need the index

for (int i = 0; i < scores.length; i++) {
    System.out.println("Student " + i + 
        ": " + scores[i]);
}
// Use i < scores.length, NOT <=

For-Each — cleanest for reading

for (int score : scores) {
    System.out.println("Score: " + score);
}
// No index variable needed
// Can't modify the array with this

💡 Which to use? Use for-each when you just need to read every element. Use the standard for when you need the index (e.g., "item 3 of 10") or need to modify elements.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // 1. Create and access
        int[] scores = {85, 92, 78, 95, 88};
        System.out.println("1. ARRAY ACCESS:");
        System.out.println("   scores = " + Arrays.toString(scores));
        System.out.println("   Length: " + scores.length);
        System.out.println("   First (index 0): " + scores[0]);
        System.out.println("   Third (index 2): " + scores[2]);
        System.out.println("   Last: " + scores[scores.length - 1]);

        // 2. Modify an element
        scores[2] = 82;
        System.out.println("\n2. MODIFY:");
        System.out.println("   Changed index 2 from 78 to 82");
        System.out.println("   scores = " + Arrays.toString(scores));

        // 3. Standard for loop (with index)
        System.out.println("\n3. FOR LOOP (with index):");
        for (int i = 0; i < scores.length; i++) {
            System.out.println("   Student " + i + ": " + scores[i]);
        }

        // 4. For-each loop
        System.out.println("\n4. FOR-EACH LOOP:");
        for (int score : scores) {
            String grade = score >= 90 ? "A" : score >= 80 ? "B" : "C";
            System.out.println("   Score: " + score + " (" + grade + ")");
        }

        // 5. Default values: a new int[] is filled with zeros
        int[] empty = new int[5];
        System.out.println("\n5. DEFAULT VALUES:");
        System.out.println("   new int[5] defaults to: " + Arrays.toString(empty));
    }
}

4️⃣ Common Array Operations

These operations come up constantly in real programming. Master these patterns and you'll solve 80% of array problems:

int[] scores = {85, 92, 78, 95, 88};

// Sum all elements
int sum = 0;
for (int score : scores) sum += score;
System.out.println("Sum: " + sum);  // 438

// Calculate average (cast to double for decimal result!)
double average = (double) sum / scores.length;
System.out.println("Average: " + average);  // 87.6

// Find maximum and minimum
int max = scores[0];
int min = scores[0];
for (int score : scores) {
    if (score > max) max = score;
    if (score < min) min = score;
}
System.out.println("Max: " + max);  // 95
System.out.println("Min: " + min);  // 78

// Linear search — find a value
int target = 92;
int foundAt = -1;  // -1 means "not found"
for (int i = 0; i < scores.length; i++) {
    if (scores[i] == target) {
        foundAt = i;
        break;
    }
}
System.out.println("Found " + target + " at index " + foundAt);

5️⃣ The Arrays Utility Class

Java provides java.util.Arrays with ready-made methods for common array tasks. Always use these instead of writing your own:

import java.util.Arrays;

int[] data = {42, 17, 93, 8, 55};

// Sort (ascending, in-place — modifies original!)
Arrays.sort(data);
// data is now {8, 17, 42, 55, 93}

// Print readable representation
System.out.println(Arrays.toString(data));
// → "[8, 17, 42, 55, 93]"

// Copy an array
int[] copy = Arrays.copyOf(data, data.length);  // full copy
int[] first3 = Arrays.copyOf(data, 3);          // first 3 elements

// Fill all elements with a value
int[] zeros = new int[10];
Arrays.fill(zeros, -1);  // all elements become -1

// Compare two arrays
boolean same = Arrays.equals(data, copy);  // true (same content)

// Binary search (array MUST be sorted first!)
int index = Arrays.binarySearch(data, 42);  // returns 2

⚠️ Common trap: System.out.println(arr) prints a memory address like [I@1b6d3586, not the values! Always use Arrays.toString(arr) to print arrays.

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] scores = {85, 92, 78, 95, 88, 72, 91, 65, 83, 97};
        System.out.println("Scores: " + Arrays.toString(scores) + "\n");

        // 1. Sum and average
        int sum = 0;
        for (int s : scores) sum += s;
        double avg = (double) sum / scores.length;
        System.out.println("1. SUM & AVERAGE:");
        System.out.println("   Sum: " + sum);
        System.out.printf("   Average: %.1f%n", avg);

        // 2. Max and min (tracking the index of each)
        int max = scores[0], min = scores[0], maxIdx = 0, minIdx = 0;
        for (int i = 0; i < scores.length; i++) {
            if (scores[i] > max) { max = scores[i]; maxIdx = i; }
            if (scores[i] < min) { min = scores[i]; minIdx = i; }
        }
        System.out.println("\n2. MAX & MIN:");
        System.out.println("   Max: " + max + " (index " + maxIdx + ")");
        System.out.println("   Min: " + min + " (index " + minIdx + ")");

        // 3. Linear search
        System.out.println("\n3. LINEAR SEARCH:");
        int target = 91, foundAt = -1;
        for (int i = 0; i < scores.length; i++) {
            if (scores[i] == target) { foundAt = i; break; }
        }
        System.out.println("   Search for " + target + ": " +
            (foundAt >= 0 ? "Found at index " + foundAt : "Not found"));

        // 4. Sort a copy (Arrays.sort is in-place, so copy first)
        int[] sorted = Arrays.copyOf(scores, scores.length);
        Arrays.sort(sorted);
        System.out.println("\n4. SORTED:");
        System.out.println("   " + Arrays.toString(sorted));

        // 5. Grade distribution
        System.out.println("\n5. PASSING (>=70):");
        int passing = 0;
        for (int s : scores) if (s >= 70) passing++;
        System.out.println("   " + passing + " of " + scores.length + " passed");
    }
}

6️⃣ 2D Arrays — Tables and Grids

A 2D array is an "array of arrays" — think of it as a table with rows and columns. Each element is accessed with two indices: [row][column]. They're used for game boards, spreadsheets, images, and mathematical matrices.

// Create a 3×4 matrix
int[][] matrix = {
    {1, 2, 3, 4},     // row 0
    {5, 6, 7, 8},     // row 1
    {9, 10, 11, 12}   // row 2
};

// Access: matrix[row][column]
matrix[0][0]   // 1  (top-left)
matrix[1][2]   // 7  (row 1, column 2)
matrix[2][3]   // 12 (bottom-right)

// Dimensions
matrix.length        // 3 (number of rows)
matrix[0].length     // 4 (number of columns)

// Iterate with nested loops
for (int row = 0; row < matrix.length; row++) {
    for (int col = 0; col < matrix[row].length; col++) {
        System.out.print(matrix[row][col] + "\t");
    }
    System.out.println();
}

7️⃣ Arrays vs ArrayList

A common question: when should you use an array vs an ArrayList? Here's the decision guide:

FeatureArrayArrayList
SizeFixed — can't changeDynamic — grows/shrinks
SpeedSlightly fasterSlightly slower
Primitives✅ int, double, etc.❌ Objects only (Integer)
Add/Remove❌ Can't✅ .add(), .remove()
Best forKnown-size dataGrowing collections

Rule of thumb: Use arrays when the size is known and won't change (days of week, game board). Use ArrayList when you need to add/remove items (shopping cart, to-do list).

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // 1. Multiplication table (5x5)
        System.out.println("1. MULTIPLICATION TABLE (5x5):");
        for (int i = 1; i <= 5; i++) {
            StringBuilder row = new StringBuilder();
            for (int j = 1; j <= 5; j++) {
                row.append(String.format("%4d", i * j));
            }
            System.out.println("  " + row);
        }

        // 2. Seating chart (2D String array)
        System.out.println("\n2. SEATING CHART:");
        String[][] seats = {
            {"Alice", "Bob",   "Carol"},
            {"Dave",  "Eve",   "Frank"},
            {"Grace", "Henry", "Iris"}
        };
        for (int row = 0; row < seats.length; row++) {
            StringBuilder rowStr = new StringBuilder("  Row " + (row + 1) + ": ");
            for (int col = 0; col < seats[row].length; col++) {
                rowStr.append(String.format("%-8s", seats[row][col]));
            }
            System.out.println(rowStr);
        }
        System.out.println("  seats[1][2] = " + seats[1][2] + " (Row 2, Seat 3)");

        // 3. Matrix sum
        System.out.println("\n3. MATRIX SUM:");
        int[][] matA = {{1, 2}, {3, 4}};
        int[][] matB = {{5, 6}, {7, 8}};
        int[][] matSum = new int[matA.length][matA[0].length];
        for (int i = 0; i < matA.length; i++) {
            for (int j = 0; j < matA[i].length; j++) {
                matSum[i][j] = matA[i][j] + matB[i][j];
            }
        }
        System.out.println("  A+B = " + Arrays.deepToString(matSum));

        // 4. Search a 2D array
        System.out.println("\n4. SEARCH 2D ARRAY:");
        int[][] grid = {{10, 20, 30}, {40, 50, 60}, {70, 80, 90}};
        int searchFor = 50;
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                if (grid[r][c] == searchFor) {
                    System.out.println("  Found " + searchFor + " at [" + r + "][" + c + "]");
                }
            }
        }
    }
}
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        // 🎯 YOUR TURN — replace each ___ using the hint beside it.

        // 1) Seven slots, all starting at 0.
        int[] rainfall = new ___[7];              // 👉 replace ___ with int
        rainfall[0] = 4;
        rainfall[1] = 0;
        rainfall[2] = 12;
        rainfall[3] = 3;
        rainfall[4] = 0;
        rainfall[5] = 8;
        rainfall[6] = 1;

        // 2) How many slots? It is a field, not a method — no brackets.
        System.out.println("Days recorded: " + rainfall.___);   // 👉 replace ___ with length

        int total = 0;
        int wettest = rainfall[0];
        // 3) Read every value without touching an index at all.
        for (int mm : ___) {                      // 👉 replace ___ with rainfall
            total += mm;
            if (mm > wettest) wettest = mm;
        }
        System.out.println("Total mm: " + total);
        System.out.println("Wettest day: " + wettest + " mm");

        // 4) sort() rearranges IN PLACE, so sort a copy to keep the original.
        int[] sorted = Arrays.___(rainfall, rainfall.length);   // 👉 replace ___ with copyOf
        Arrays.sort(sorted);
        System.out.println("Sorted:   " + Arrays.toString(sorted));
        System.out.println("Original: " + Arrays.toString(rainfall));

        String[][] week = {
            {"Mon", "dry"},
            {"Tue", "wet"}
        };
        // 5) Row first, then column — both counted from 0.
        System.out.println("Tue was " + week[1][___]);           // 👉 replace ___ with 1
    }
}

Common Mistakes

int[] arr = new int[5];
arr[5] = 10;  // ❌ Index 5 doesn't exist! Valid: 0-4
arr[arr.length] = 10;  // ❌ Same bug — use arr.length - 1
System.out.println(arr);           // ❌ Prints "[I@1b6d3586"
System.out.println(Arrays.toString(arr)); // ✅ Prints "[1, 2, 3]"

Pro Tips

💡 Default values: int[] defaults to 0, boolean[] to false, double[] to 0.0, String[] to null.

💡 Use .length not .length(): Arrays use a property (arr.length), strings use a method (str.length()). Don't mix them up!

💡 Prefer for-each for reading: It's cleaner and prevents off-by-one errors. Only use standard for when you need the index.

💡 Always initialize before use: Accessing an uninitialized object array element gives null, which will cause NullPointerException if you call methods on it.

📋 Quick Reference

OperationSyntaxNotes
Create (values)int[] a = {1,2,3}Size inferred
Create (size)int[] a = new int[5]Defaults to 0
Accessa[index]0-based
Lengtha.lengthProperty (no parentheses)
SortArrays.sort(a)In-place, ascending
PrintArrays.toString(a)"[1, 2, 3]"
CopyArrays.copyOf(a, len)Returns new array
CompareArrays.equals(a, b)Content comparison

🎉 Lesson Complete!

You can now create, access, iterate, and manipulate arrays! You understand 0-based indexing, common operations like sum/max/min/search, 2D arrays for grids, and the Arrays utility class.

Practice quiz

What is the index of the FIRST element in a Java array?

  • 1
  • -1
  • 0
  • It depends

Answer: 0. Java arrays use 0-based indexing, so the first element is at index 0.

For 'int[] scores = {85, 92, 78, 95, 88};', what is scores[2]?

  • 78
  • 92
  • 95
  • 85

Answer: 78. Index 2 is the third element, which is 78.

How do you get the number of elements in an array named arr?

  • arr.length()
  • arr.size()
  • length(arr)
  • arr.length

Answer: arr.length. Arrays use the .length property (no parentheses); Strings use .length() with parentheses.

What are the default values in 'int[] temps = new int[7];'?

  • null
  • 0
  • -1
  • Undefined

Answer: 0. A new int array is filled with zeros; object arrays default to null and boolean[] to false.

What exception does accessing scores[5] throw on a 5-element array?

  • ArrayIndexOutOfBoundsException
  • NullPointerException
  • ArithmeticException
  • No exception

Answer: ArrayIndexOutOfBoundsException. Valid indices are 0–4; index 5 throws ArrayIndexOutOfBoundsException.

How do you reliably access the LAST element of an array arr?

  • arr[arr.length]
  • arr[-1]
  • arr[arr.length - 1]
  • arr.last()

Answer: arr[arr.length - 1]. The last valid index is arr.length - 1; arr[arr.length] is out of bounds.

What does System.out.println(arr) print for an int array?

  • The elements like [1, 2, 3]
  • A memory address like [I@1b6d3586
  • An error
  • The length

Answer: A memory address like [I@1b6d3586. println on an array prints a hashcode-style memory reference; use Arrays.toString(arr) for values.

What does Arrays.sort(data) do?

  • Returns a new sorted array
  • Sorts descending
  • Removes duplicates
  • Sorts the array in place, ascending

Answer: Sorts the array in place, ascending. Arrays.sort sorts the array in place (modifying the original) in ascending order.

How do you access the element at row 1, column 2 of a 2D array 'matrix'?

  • matrix[1,2]
  • matrix[1][2]
  • matrix(1)(2)
  • matrix[2][1]

Answer: matrix[1][2]. 2D arrays use [row][column] indexing, so matrix[1][2].

Once created, can a Java array change its size?

  • Yes, with add()
  • Only if it is an int array
  • No, the size is fixed
  • Only with a loop

Answer: No, the size is fixed. Array size is fixed at creation; use an ArrayList when you need a resizable collection.

Continue this course