← Chapter 5 — Arrays, Memory & Methods

19. Arrays

mixed

Description

An array stores a fixed number of values of one type. Each value has an index, beginning at zero.

Arrays are useful when the size is known. Later, collections such as ArrayList provide more flexible resizing.

Subtopics

Creating arrays

Description

An array declaration includes brackets.

Explanation

You can provide values immediately or create a chosen size.

Example

int[] scores = {82, 91, 76};

Reading elements

Description

Use an index in brackets.

Explanation

Valid indexes go from 0 to length - 1.

Example

int first = scores[0];

Explanation

Accessing an invalid index causes ArrayIndexOutOfBoundsException. A loop condition using i < array.length is a safe, standard pattern.

Example

public class ArrayDemo {
    public static void main(String[] args) {
        int[] scores = {82, 91, 76};
        for (int score : scores) {
            System.out.println(score);
        }
    }
}

Key points

  • Array indexes start at zero.
  • Arrays have a fixed length.
  • All elements have the same type.

Video

Open video

Open reference