In the previous section, we mentioned that creating an array requires two steps: declaring the array and allocating elements to the array . In this section we mainly learn how to allocate elements to the array.
Declaring an array only gives the name of the array variable and the data type of the elements. To actually use the array, you must create the array, that is, allocate elements to the array.
The format for allocating elements to an array is as follows:
Array name = new array element type [number of array elements];
For example:
boy=newfloat[4];
After allocating elements to the array, the array boy obtains 4 variables used to store float type data, that is, 4 float type elements. The first address of these elements is stored in the array variable boy. This address is called a reference to the array , so that the array can use the variables assigned to it through indexing, that is, to operate on its elements.
Arrays are reference variables. The array variable stores the address of the first element of the array. The elements of the array are used by adding the name of the array variable and indexing, for example:
boy[0]=12;boy[1]=23.908F;boy[2]=100;boy[3]=10.23f;
Declaring an array and creating an array can be done together, for example:
floatboy[]=newfloat[4];
Two-dimensional arrays, like one-dimensional arrays, must use the new operator to allocate elements to the array after declaration. For example:
intmytwo[][];mytwo=newint[3][4];
or
intmytwo[][]=newint[3][4];
Java uses "array of arrays" to declare multi-dimensional arrays . A two-dimensional array is composed of several one-dimensional arrays. For example, the two-dimensional array mytwo created above is composed of three one-dimensional arrays of length 4, mytwo[0], mytwo[1], and mytwo[2].
The one-dimensional arrays that make up the two-dimensional array do not have to have the same length. When creating the two-dimensional array, you can specify the lengths of the one-dimensional arrays that make up the two-dimensional array, for example:
inta[][]=newint[3][];
A two-dimensional array a is created. a consists of three one-dimensional arrays a[0], a[1] and a[2], but their lengths have not been determined yet, that is, elements have not been allocated to these one-dimensional arrays. Therefore, three one-dimensional arrays of a must be created, for example:
a[0]=newint[6];a[1]=newint[12];a[2]=newint[8];
Note : Unlike the C language, Java allows you to use the value of an int variable to specify the number of elements in an array, for example:
intsize=30;doublenumber[]=newdouble[size];