Each single element of an array object can be accessed as if it were a separate variable.
Syntax:
wherearrayName[index]
Semantics:
Accesses the element of the array arrayName in the position specified by index to read or modify it.
If the array arrayName contains N elements, the evaluation of the expression index must return an integer in the interval [0, N - 1]; if this is not the case, a runtime error occurs when the program is run.
Example:
int[] a; // a is a variable of type array of integers a = new int[5]; // creation of an array object with 5 elements of type int; // the array object is referenced by the array variable a a[0] = 23; // assignment to the first element of the array a[4] = 92; // assignment to the last element of the array a[5] = 16; // ERROR! the index 5 is not in the range [0,4]
Note: It is very important to remember that, when an array contains N elements (N = 5 in the example), the indexes used to access the elements must necessarily be integers in the interval [0, N - 1]. Otherwise, a runtime error occurs when the program is executed. In the example, an error is signaled when the statement a[5]=16;.