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:
[] ;
Or[];
wherecan 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.
= new[]; - The array declaration and construction can be combined.
[] = new []; - Initializing an Array: Java provides the means of declaring, constructing, and explicitly initializing an array in one declaration statement:
[] = { }; - 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:
[] - Anonymous Arrays:
[] = new [] { };
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:
[][]...[] ;
or[][]...[];