TExcelTAD
Home › Java › Java Arrays

Java Arrays

An array stores a fixed number of values of the same type in a single variable. Instead of creating score1, score2, score3..., you create one array scores and reach each value by its index, starting at 0.

Creating arrays

There are two ways: list the values directly, or give a size and fill it later.

java · try it yourself
class Main {
    public static void main(String[] args) {
        String[] fruits = {"apple", "banana", "cherry"};
        int[] counts = new int[4];      // four ints, all 0 to start
        counts[0] = 12;
        counts[3] = 7;

        System.out.println(fruits[0]);
        System.out.println(fruits[2]);
        System.out.println(fruits.length);
        System.out.println(counts[1] + " " + counts[3]);

        fruits[1] = "blueberry";        // change an element
        System.out.println(fruits[1]);
    }
}
apple
cherry
3
0 7
blueberry

Arrays created with new are filled with default values: 0 for numbers, false for booleans and null for objects such as strings. Note that length is a field, not a method — no parentheses.

Looping through an array

java · try it yourself
class Main {
    public static void main(String[] args) {
        double[] temps = {21.5, 23.0, 19.8, 25.1, 22.4};

        // classic for: you have the index
        for (int i = 0; i < temps.length; i++) {
            System.out.println("Day " + (i + 1) + ": " + temps[i]);
        }

        // for-each: you only need the values
        double sum = 0;
        double max = temps[0];
        for (double t : temps) {
            sum += t;
            if (t > max) max = t;
        }
        System.out.printf("Average %.2f, max %.1f%n", sum / temps.length, max);
    }
}
Day 1: 21.5
Day 2: 23.0
Day 3: 19.8
Day 4: 25.1
Day 5: 22.4
Average 22.36, max 25.1

Index out of bounds

Valid indexes are 0 to length - 1. Accessing anything else throws an ArrayIndexOutOfBoundsException at runtime:

java · try it yourself
class Main {
    public static void main(String[] args) {
        int[] data = {10, 20, 30};
        try {
            System.out.println(data[3]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
Error: Index 3 out of bounds for length 3

The Arrays helper class

java.util.Arrays provides ready-made tools for printing, sorting, searching, filling and copying:

java · try it yourself
import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        int[] nums = {42, 7, 19, 3, 25};
        System.out.println(Arrays.toString(nums));

        int[] copy = Arrays.copyOf(nums, nums.length);
        Arrays.sort(copy);
        System.out.println(Arrays.toString(copy));
        System.out.println("19 is at index " + Arrays.binarySearch(copy, 19));

        int[] zeros = new int[5];
        Arrays.fill(zeros, 9);
        System.out.println(Arrays.toString(zeros));
        System.out.println(Arrays.equals(nums, copy));
    }
}
[42, 7, 19, 3, 25]
[3, 7, 19, 25, 42]
19 is at index 2
[9, 9, 9, 9, 9]
false

Printing an array directly with System.out.println(nums) shows only a type code and a hash, such as [I@1b6d3586 — never what you want. Always use Arrays.toString.

Multidimensional arrays

An array can hold other arrays. A 2-D array is like a table with rows and columns:

java · try it yourself
import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        int[][] seats = {
            {1, 0, 1},
            {0, 0, 1},
            {1, 1, 1}
        };
        System.out.println("Row 1, seat 2: " + seats[1][2]);
        int taken = 0;
        for (int[] row : seats) {
            for (int seat : row) {
                taken += seat;
            }
        }
        System.out.println("Seats taken: " + taken);
        System.out.println(Arrays.deepToString(seats));
    }
}
Row 1, seat 2: 1
Seats taken: 6
[[1, 0, 1], [0, 0, 1], [1, 1, 1]]

Note: An array's size is fixed once created. If you need a list that grows and shrinks, use ArrayList (covered in the Data Structures section).

Test yourself

What is the index of the last element of an array a?

  1. a.length
  2. a.length - 1
  3. a.length()
  4. -1

What values does new boolean[3] contain?

  1. true, true, true
  2. null, null, null
  3. false, false, false
  4. Random values

How do you print the contents of int[] a as [1, 2, 3]?

  1. System.out.println(a)
  2. System.out.println(a.toString())
  3. System.out.println(Arrays.toString(a))
  4. System.out.println(a.print())