Java ยท Chapter 17 of 42

Java Arrays

An array is a fixed-size, ordered collection of elements of the same type. Arrays in Java are objects, and their length is fixed once created; it's accessed via the .length field (not a method).

Arrays can be one-dimensional or multi-dimensional, allowing you to model grids and tables of data.

Syntax
int[] arr = new int[5];
int[] arr2 = {1, 2, 3};
arr[0] = 10;

Declaring and accessing arrays

Arrays are declared with `type[] name = new type[size];` or with an array literal `{1, 2, 3}`. Elements are accessed with zero-based indices.

Multi-dimensional arrays

A 2D array like `int[][] grid` is an array of arrays, useful for representing tables, matrices, or grids.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    int[] nums = {10, 20, 30};
    System.out.println(nums[1]);
    System.out.println(nums.length);
    nums[0] = 99;
    System.out.println(nums[0]);
  }
}
Output
20
3
99

Elements are accessed by index, length gives the array size, and elements can be reassigned.

Key points

  • Arrays have a fixed size once created.
  • Indices start at 0.
  • length is a field, not a method, on arrays.
  • 2D arrays are arrays of arrays.
๐Ÿ’ก Note: Accessing an index outside the array bounds throws ArrayIndexOutOfBoundsException.

๐Ÿ“ Quick Quiz

1. What index does the first array element have?

2. How do you get an array's size?

3. What exception is thrown for an invalid index?