Array Basics

An array stores a fixed number of values of one type. Its indexes start at zero, so an array of length three has indexes 0, 1, and 2.

Array length is fixed when the array is created, but individual elements can change. Use a collection later when the number of elements must grow or shrink.

Create and update an array

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] marks = {72, 81, 65};
        System.out.println(marks[0]);
        marks[1] = 90;
        System.out.println(marks[1]);
        System.out.println(marks.length);
        System.out.println(Arrays.toString(marks));

        int[] bonus = new int[3];
        System.out.println(Arrays.toString(bonus));
    }
}

Output:

72
90
3
[72, 90, 65]
[0, 0, 0]

Index 0 reads the first mark. Index 1 changes the second mark, and length reports that the array still has three positions.

Printing an array variable directly does not show its elements. Arrays.toString(array) formats all the elements for readable output, after import java.util.Arrays; at the top of the file.

new int[3] creates an array when you know the size but not the values yet. Every element of a new int array starts at 0.

Create and update an array of marks.