Java Tutorial · Control Flow · Lesson 16 of 37

Java Arrays

Create arrays, access elements, loop, sort and use 2D arrays.

Creating arrays

Arrays hold a fixed number of values of one type. Indexes start at 0:

Example 1
public class Main {
    public static void main(String[] args) {
        String[] cars = {"Volvo", "BMW", "Ford"};
        int[] scores = new int[3];   // filled with 0
        scores[0] = 90;
        cars[1] = "Tesla";
        System.out.println(cars[1] + " " + cars.length + " " + scores[0] + " " + scores[2]);
        for (int i = 0; i < cars.length; i++) {
            System.out.println(i + ": " + cars[i]);
        }
    }
}

Output

Tesla 3 90 0
0: Volvo
1: Tesla
2: Ford

Run this on your computer — see “Get Started” for setup.

Accessing an index outside the array throws ArrayIndexOutOfBoundsException.

The Arrays helper class

java.util.Arrays sorts, searches, fills, copies and prints arrays:

Example 2
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = {42, 7, 19, 3};
        Arrays.sort(nums);
        System.out.println(Arrays.toString(nums));
        System.out.println(Arrays.binarySearch(nums, 19));
        int[] copy = Arrays.copyOf(nums, 6);
        System.out.println(Arrays.toString(copy));
        System.out.println(Arrays.stream(nums).sum());
    }
}

Output

[3, 7, 19, 42]
2
[3, 7, 19, 42, 0, 0]
71

Run this on your computer — see “Get Started” for setup.

Multidimensional arrays

Example 3
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] grid = {
            {1, 2, 3},
            {4, 5, 6},
        };
        System.out.println(grid[1][2]);
        for (int[] row : grid) {
            System.out.println(Arrays.toString(row));
        }
        System.out.println(Arrays.deepToString(grid));
    }
}

Output

6
[1, 2, 3]
[4, 5, 6]
[[1, 2, 3], [4, 5, 6]]

Run this on your computer — see “Get Started” for setup.

Need a list that can grow? Use ArrayList.

Test yourself

Can a Java array change its size after it's created?

  1. Yes
  2. No
Show answer

Answer: No

Practice next