There are two syntaxes for defining arrays in Java:
type arrayName[];
type[] arrayName;
type is any data type in Java, including basic types and combined types
arrayName is the array name and must be a legal identifier
[ ] indicates that the variable is an array type variable
For example:
int demoArray[];
int[] demoArray;
There is no difference between these two forms, and the usage effect is exactly the same. Readers can use it according to their own Programming habits selection.
Unlike C and C, Java does not allocate memory for array elements when defining an array, so there is no need to specify the number of array elements, that is, the array length, in [ ].
And for an array defined above, we cannot access any of its elements. We must allocate memory space for it. In this case, we need to use operator new.
The format is as follows:
arrayName=new type[arraySize];
Among them, arraySize is the length of the array, and type is the type of the array.
For example:
demoArray=new int[3];
Allocate the memory space occupied by 3 int type integers for an integer array.
Usually, you can allocate space while defining, the syntax is:
type arrayName[] = new type[arraySize];
For example:
int demoArray[] = new int[3];
Related learning recommendations: java basic tutorial
The above is the detailed content of How to use arrays. For more information, please follow other related articles on the PHP Chinese website!