An array is a special object containing a group of contigious memory locations that have the same name and the same type and a separate variable containing an integer constant equal to the number of array elements. The elements of Java arrays are numbered starting from 0.
An array must be created before it can be used. We first declare a reference or "handle" to an array that permits Java to locate the object in memory when it is needed. Then we create an array object to assign to the reference using the new operator. For example, we can write double x[]; // create an array reference
x = new double[5]; // create array object
Or we can create an array reference and an array object on a single line: double x[] = new double[5];
The number of elements in the array x is x.length. The elements of the array are written as x[0], x[1], x[2], x[3], x[4].
An array object may be created and initialized when its reference is declared. For example, double x[] = {1.0, 1.4, 1.6, 1.8, 3.0};
It is a good idea to declare array sizes using named constants (final variables) so that the length of the arrays can be easily changed. final int ARRAY_SIZE = 1000;
double x[] = new double[ARRAY_SIZE];
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment