CodeBlanks Logo Icon CodeBlanks

Array access

Learn access with arr[i] and length.

Array access

Array elements are accessed by index. Indexes start at 0: arr[0] is the first, arr[1] the second element.

int[] arr = {10, 20, 30};
System.out.println(arr[0]);   // 10
System.out.println(arr.length); // 3

The index is between 0 and length - 1. Going beyond throws ArrayIndexOutOfBoundsException. arr.length is a field (no parens); ArrayList.size() is a method.

Index bounds

Array indexes start at 0 and go up to length - 1. Going beyond throws:

int[] arr = new int[3];  // indexes 0, 1, 2
arr[0] = 10;  // valid
arr[2] = 30;  // valid (last)
arr[3] = 40;  // ERROR!

So loops use i < arr.length, not i <= arr.length. The array size is fixed; arr.length never changes.

Practice Print the first element and size

Write a Main class with a main method. Assign the literal {10, 20, 30} to int[] arr. Print the first element with System.out.println(arr[0]) and the size with System.out.println(arr.length).

Sample solution

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

Expected output

10
3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Access the first element

Question
int first = arr[____];
Answer
int first = arr[0];

Explanation: arr[0] gives the first element.

2 int[] arr = new int[3]; arr[3] = 5; — what happens?

  • Changes the last element
  • Changes the first element
  • Throws an error Correct answer
  • Valid assignment

Explanation: arr[3] is out of bounds; it throws.

3 Match the access concepts

Term Meaning
arr[0] First element
arr[i] i-th element
arr.length Size
length-1 Last index

All lessons in Beginner