The following program will introduce you to some of the syntax and usage of the array class in Java:
Code Sample 16-1
int[] A = new int[6]; // an array of 6 integers
int loop;
for (loop = 0; loop < 6; loop++){
A[loop] = loop * loop;
}
System.out.println("The contents of array A are:");
System.out.println();
for (loop = 0; loop < 6; loop++){
System.out.print(" " + A[loop]);
}
System.out.println();
Run output:
The contents of array A are:
0 1 4 9 16 25
An array is similar to the ArrayList. It is a linear data structure composed of adjacent memory locations, or “cells”, each holding values of the same type.
The variable A is an array, a group of 6 related scalar values. There are six locations in this array referenced by indexes 0 to 5. Note that indexes always start at zero, and count up by one until the last slot of the array. If there are N slots in an array, the indexes will be 0 through N-1 (for example, if N=6, the indexes are 0 through 5 or (N-1)).
The variable loop
is used in a for
loop to reference indexes 0 through 5. In this program, the square of each index is stored in the memory location occupied by each cell of the array. The syntax for accessing a memory location of an array requires the use of square brackets []
.
The square brackets []
are collectively an operator in Java, and are called the index operator. They are similar to the parentheses as they have the highest level of precedence compared to all other operators.
The index operator performs automatic bounds checking. Bounds checking makes sure that the index is within the range for the array being referenced. Whenever a reference to an array element is made, the index must be greater than or equal to zero and less than the size of the array. If the index is not valid, the exception ArrayIndexOutOfBoundsException
is thrown.
Last modified: December 12, 2022