Arrays in Java
An array is a data structure that defines an indexed collection of a fixed number of homogeneous data elements. All elements in the array have the same data type. A position in the array is indicated by a non-negative integer value called the index. An element at a given position in the array is accessed using the index. The size of an array is fixed and cannot increase to accommodate more elements.
- In Java, arrays are objects. Arrays can be of primitive data types or reference types.
- In the first case, all elements in the array are of a specific primitive data type. In the second case, all elements are references of a specific reference type.
- Each array object has a final field called length, which specifies the array size, that is, the number of elements the array can accommodate. The first element is always at index 0 and the last element at index n-1, where n is the value of the length field in the array.
- Simple arrays are one-dimensional arrays.
- An array variable declaration has either the following syntax:<element type>[] <array name>;
Or
<element type> <array name>[];
where <element type> can be a primitive data type or a reference type .
The declaration does not actually create an array. It only declares a reference that can denote an array object.
- Constructing an Array: An array can be constructed for a specific number of elements of the element type, using the new operator. The resulting array reference can be assigned to an array variable of the corresponding type.
<array name> = new <element type> [<array size>]; - The array declaration and construction can be combined. <element type1>[] <array name> = new <element type2>[<array size>];
- Initializing an Array: Java provides the means of declaring, constructing, and explicitly initializing an array in one declaration statement:
<element type>[] <array name> = { <array initialize list> }; - Using an Array: The whole array is referenced by the array name, but individual array elements are accessed by specifying an index with the [] operator. The array element access expression has the following syntax:
<array name> [<index expression>] - Anonymous Arrays:
<element type>[] <array name> = new <element type>[] { <array initialize list> };
can be used to declare an array for example
int[] myArray = new int[] {1, 4, 6, 8}; - Multidimensional Arrays: An array element can be an object reference and arrays are objects, array elements can themselves reference other arrays. In Java, an array of arrays can be defined as follows:
<element type>[][]...[] <array name>;
or <element type> <array name>[][]...[];