Arrays

Core Java · lesson 5 of 42 · 3 min read

Create, index and sort fixed-size arrays, and know when to reach for a List instead.

Open this lesson in the learning hub

Key points

  • An array is a fixed-size block of one type. The size is set at creation and length is a field, not a method.
  • Indexes start at 0. Reading past the end throws ArrayIndexOutOfBoundsException.
  • New arrays come pre-filled: 0 for numbers, false for booleans, null for object types.
  • Arrays.toString() prints, Arrays.sort() sorts in place, Arrays.copyOf() resizes into a new array.
  • A 2D array is an array of arrays, so rows may differ in length. Print it with Arrays.deepToString().
  • Printing an array directly gives something like [I@1b6d — that is the default toString, not the contents.

Example

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] nums = {5, 3, 9, 1};
        System.out.println("length: " + nums.length + ", first: " + nums[0]);

        Arrays.sort(nums);
        System.out.println("sorted: " + Arrays.toString(nums));
        System.out.println("binarySearch(9): index " + Arrays.binarySearch(nums, 9));

        int[] bigger = Arrays.copyOf(nums, 6);
        System.out.println("copyOf pads with 0: " + Arrays.toString(bigger));

        String[] blanks = new String[3];
        System.out.println("object arrays start null: " + Arrays.toString(blanks));

        int[][] grid = {{1, 2}, {3, 4, 5}};
        System.out.println("jagged grid: " + Arrays.deepToString(grid) + ", row 1 length " + grid[1].length);

        try {
            System.out.println(nums[9]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("out of bounds -> " + e.getMessage());
        }
    }
}

Arrays are fixed-size and fast; use a List when the size has to change.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.