Java Arrays

Store fixed-size lists of values in arrays, loop through them, use the Arrays helper class and build 2D grids.

Lesson 31 of 127Intermediate18 min read

An array stores a fixed number of values of the same type, one after another, under a single name. Instead of separate variables called score1, score2 and score3, you write one array called scores and reach each value by its position. You met arrays briefly in the loops lesson; this lesson covers them properly.

Arrays are the most basic collection in Java and they're very fast. Their one limitation is that the size is fixed when the array is created. If you need a list that grows and shrinks, the ArrayList lesson shows the flexible alternative, but arrays remain everywhere: in method parameters like String[] args, in performance-sensitive code and as the building block underneath many other collections.

In this lesson you'll create arrays, understand default values, loop through them, sort and print them with the Arrays class, copy them correctly and build two-dimensional grids.

Creating arrays

There are two ways to create an array:

Java
int[] scores = {72, 88, 95, 60};   // values known now
double[] prices = new double[5];   // 5 slots, filled with defaults
  • The type is followed by []: int[] means "array of int".
  • With new type[size], every element starts with a default value: 0 for numbers, false for booleans, '\u0000' for chars and null for objects such as Strings.
  • array.length gives the size. Note there are no brackets: length is a field, not a method like String.length().
  • Valid indexes run from 0 to length - 1. Anything else throws ArrayIndexOutOfBoundsException.

Looping through arrays

Use an index-based for loop when you need positions or want to change elements, and the enhanced for loop when you just need each value:

Java
for (int i = 0; i < scores.length; i++) {
    scores[i] += 5;               // change each element
}
for (int s : scores) {
    System.out.println(s);        // read each element
}

Changing the loop variable in an enhanced for loop, s += 5, does not change the array, because s is a copy of each value. That's a common surprise.

The Arrays helper class

java.util.Arrays provides ready-made tools for arrays:

MethodWhat it does
Arrays.toString(a)Text such as [72, 88, 95] for printing
Arrays.sort(a)Sorts the array in place, smallest first
Arrays.fill(a, 0)Sets every element to a value
Arrays.copyOf(a, n)A new array with the first n elements
Arrays.equals(a, b)true if both hold the same values in the same order
Arrays.binarySearch(a, x)Fast search in a sorted array

Printing an array directly with System.out.println(a) shows something like [I@1b6d3586, its type and memory hash, which is rarely what you want. Use Arrays.toString(a) instead.

Copying and 2D arrays

Assigning one array variable to another, int[] b = a;, does not copy the array. Both names now point to the same array, so changing b[0] also changes a[0]. To get an independent copy, use Arrays.copyOf(a, a.length) or a.clone().

A two-dimensional array is an array of arrays, perfect for grids, tables and game boards:

Java
int[][] grid = new int[3][4];   // 3 rows, 4 columns
grid[1][2] = 7;                 // row 1, column 2

grid.length is the number of rows and grid[0].length the number of columns. Nested loops visit every cell.

Arrays and methods

Arrays are objects, so a method receives a reference to the same array, not a copy. A method can therefore change the caller's array:

Java
static void doubleAll(int[] values) {
    for (int i = 0; i < values.length; i++) {
        values[i] *= 2;
    }
}

After doubleAll(scores), every element of scores has doubled. This is useful, but it can surprise callers, so name such methods clearly and document that they modify their argument. A method can also create and return a new array, static int[] firstThree(int[] a) { return Arrays.copyOf(a, 3); }, which leaves the original untouched.

The array operations and sorting and multidimensional arrays lessons build on these basics.

Java Arrays Syntax

Array syntax

type[] name = {v1, v2, v3};
type[] name = new type[size];
name[index] = value;
name.length

import java.util.Arrays;
Arrays.sort(name);
Arrays.toString(name);

type[][] grid = new type[rows][cols];
grid[r][c] = value;

Java Arrays Summary

  • int[] a = {1, 2, 3}; or new int[size]; the size can't change later.
  • New arrays are filled with defaults: 0, false or null.
  • Indexes run from 0 to a.length - 1; length has no brackets.
  • Arrays.toString, sort, fill, copyOf and equals save a lot of code.
  • b = a shares one array; copy with Arrays.copyOf. 2D arrays are arrays of arrays.

Java Arrays Examples

Each example shows the code, the output it produces and what each part does.

Example 1

Test scores

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 95, 61, 88, 79};

        int total = 0;
        for (int s : scores) {
            total += s;
        }
        double average = (double) total / scores.length;

        Arrays.sort(scores);
        System.out.println("Sorted: " + Arrays.toString(scores));
        System.out.println("Lowest: " + scores[0] + ", highest: " + scores[scores.length - 1]);
        System.out.printf("Average: %.1f%n", average);
    }
}
Output
Sorted: [61, 72, 79, 88, 95]
Lowest: 61, highest: 95
Average: 79.0
Line-by-line explanation
  1. Lines 8 to 10The enhanced for loop adds up every score.
  2. Line 11Casting to double before dividing keeps the decimal part.
  3. Line 13Arrays.sort reorders the array itself.
  4. Line 15After sorting, the first and last elements are the extremes.
Example 2

Defaults and the sharing trap

Java
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] names = new String[3];
        boolean[] done = new boolean[3];
        System.out.println(Arrays.toString(names) + " " + Arrays.toString(done));

        int[] original = {1, 2, 3};
        int[] alias = original;
        int[] copy = Arrays.copyOf(original, original.length);

        alias[0] = 99;
        System.out.println(Arrays.toString(original));
        System.out.println(Arrays.toString(copy));
    }
}
Output
[null, null, null] [false, false, false]
[99, 2, 3]
[1, 2, 3]
Line-by-line explanation
  1. Lines 5 to 6New arrays are filled with default values.
  2. Line 10alias points to the same array as original.
  3. Line 11copy is a separate array with the same values.
  4. Lines 13 to 15Changing alias changes original, but copy is untouched.
Example 3

A small 2D grid

Java
public class Main {
    public static void main(String[] args) {
        char[][] board = new char[3][3];
        for (int r = 0; r < board.length; r++) {
            for (int c = 0; c < board[r].length; c++) {
                board[r][c] = '.';
            }
        }
        board[0][0] = 'X';
        board[1][1] = 'O';
        board[2][0] = 'X';

        for (char[] row : board) {
            System.out.println(new String(row));
        }
    }
}
Output
X..
.O.
X..
Line-by-line explanation
  1. Line 3Three rows of three chars, like a noughts and crosses board.
  2. Lines 4 to 8Nested loops fill every cell with a dot.
  3. Lines 9 to 11Place three moves using row and column indexes.
  4. Lines 13 to 15Each row is a char array, which new String(...) turns into text.

Common Java Arrays Mistakes

Using <= with length

Don't
for (int i = 0; i <= scores.length; i++) {
    System.out.println(scores[i]);   // ArrayIndexOutOfBoundsException
}
Do
for (int i = 0; i < scores.length; i++) {
    System.out.println(scores[i]);
}

Printing an array directly

Don't
System.out.println(scores);              // [I@6d06d69c
Do
System.out.println(Arrays.toString(scores));   // [72, 88, 95]

Expecting = to copy an array

Don't
int[] backup = scores;
scores[0] = 0;          // backup[0] is now 0 too
Do
int[] backup = scores.clone();
scores[0] = 0;          // backup is unchanged

Java Arrays in Real Projects

Arrays in practice

Image-processing code stores pixels in large 2D arrays, games keep their boards and maps in grids, and the String[] args in every main method is an array of the words typed after the program name on the command line. Many higher-level collections, including ArrayList, use an array internally.

Java Arrays FAQ

How do I find the length of an array in Java?

Use the length field without brackets: scores.length. For a 2D array, grid.length gives the number of rows and grid[0].length the number of columns in the first row. Strings use the method length() and lists use size().

Can a Java array change size?

No. The size is fixed when the array is created. To "grow" an array, create a bigger one and copy the old values across, for example scores = Arrays.copyOf(scores, scores.length * 2);. If the size changes often, use an ArrayList.

How do I print a 2D array?

Arrays.toString only prints the outer array, which shows the memory codes of the rows. Use Arrays.deepToString(grid), which prints [[1, 2], [3, 4]], or nested loops for a neatly formatted grid.

How do I sort an array in descending order?

For an array of objects such as Integer[] or String[], use Arrays.sort(arr, Collections.reverseOrder()). For a primitive int[], sort it with Arrays.sort(arr) and then read or reverse it from the end.

How do I convert an array to a list?

Arrays.asList(arr) gives a fixed-size list backed by an object array: you can change elements but not add or remove them. List.of(...) gives an unchangeable list, and new ArrayList<>(Arrays.asList(arr)) gives a list you can change freely.

Java Arrays Exercises

Answer each one and check it instantly. If you get stuck, open the hint before the answer.

Fill in the blankseasy

Complete the line so it prints the number of elements.

int[] nums = {4, 8, 15};
System.out.println(nums.);
Predict the outputeasy

What does this print?

double[] d = new double[2];
System.out.println(d[1]);
Predict the outputmedium

What does this print?

int[] a = {3, 1, 2};
int[] b = a;
Arrays.sort(b);
System.out.println(Arrays.toString(a));
Predict the outputmedium

What does this print?

int[][] g = {{1, 2, 3}, {4, 5, 6}};
System.out.println(g.length + " " + g[1][2]);
Multiple choicehard

Which line creates an independent copy of int[] a?

Java Arrays Quiz

5 questions to check what you learned.

  1. What is the last valid index of an array with 10 elements?

    • 9
    • 10
    • 11
    • 1
  2. What is the default value in a new String[] array?

    • ""
    • "null"
    • 0
    • null
  3. Which method turns an array into readable text?

    • a.toString()
    • Arrays.toString(a)
    • String.valueOf(a)
    • a.print()
  4. Can the size of a Java array change after it's created?

    • Yes, with add()
    • Only for int arrays
    • Only if it's empty
    • No, its length is fixed
  5. Why doesn't for (int s : scores) s *= 2; double the array's values?

    • Enhanced for loops can't do maths
    • scores must be final
    • s is a copy of each value, so changing it doesn't affect the array
    • It only works on ArrayList