How to use arrays

Create an array

An array initializer lists values in braces. Its length is fixed after creation.

int[] scores = {82, 91, 76};
String[] names = {"Ada", "Grace"};

Access and update elements

Indexes begin at zero and end at length - 1.

int[] scores = {82, 91, 76};
System.out.println(scores[0]);
scores[2] = 80;

Allocate default values

The new form creates a requested length. Numeric elements start at zero, booleans at false, and object references at null.

double[] prices = new double[4];
prices[0] = 3.50;
System.out.println(prices.length);

Avoid invalid indexes

Access outside the valid range throws ArrayIndexOutOfBoundsException. Use the array's length rather than hard-coded limits.