An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You've seen an example of arrays already, in the mainmethod of the "Hello World!" application. This section discusses arrays in greater detail.
Each item in an array
is called an element
, and each element is accessed by its numerical index
. As shown in the above illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class Java type, we can have an array of ints, an array of Strings, or an array of Objects. For example, an array of ints will have the type int. Similarly we can have int, which represents an "array of arrays of ints". Such an array is said to be a two-dimensional array.
int A = new int;
declares a variable, A, of type int, and it initializes that variable to refer to a newly created object. That object is an array of arrays of ints. Here, the notation int indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays.
To process a two-dimensional array, we use nested for loops. We already know about for loop. A loop in a loop is called a Nested loop. That means we can run another loop in a loop.
Notice in the following example how the rows are handled as separate objects.
In this example, "int a2 = new int;" notation shows a two-dimensional array. It declares a variable a2 of type int,and it initializes that variable to refer to a newly created object. The notation int indicates that there are 10 arrays of ints in the array a2, and that there are 5 ints in each of those arrays.
Here is the complete code of the example:
So far we have studied about the one-dimensional and two-dimensional arrays. To store data in more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These items are accessed via n subscript expressions. For example, in a language that supports it, the element of the two-dimensional array x is denoted by x[i,j].
The Java programming language does not really support multi-dimensional arrays. It does, however, supports an array of arrays. In Java, a two-dimensional array 'x' is an array of one-dimensional array. For instance :-
int x = new int;
The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to select the element from that array. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "length-1" indexed value. There is no array assignment operator.