Through previous studies, we have learned about basic data types such as int, char, double, etc. In this section we will learn about arrays.
I don’t know if you have ever thought about it, what should you do if your program requires several variables of the same type, such as 8 int-type variables? According to the knowledge we learned before, we may declare 8 int type variables:
intx1,x2,x3,x4,x5,x6,x7,x8;
However, if the program requires more int-type variables, it is not advisable to declare variables in this way, which prompts us to learn to use arrays. An array is a composite data type composed of variables of the same type in order. That is, an array is a collection of variables of the same type. We call these variables of the same type the elements or units of the array. Arrays use the elements of the array by indexing the array name.
Arrays are reference variables. Creating an array requires two steps: declaring the array and allocating elements to the array . In this section we mainly learn how to declare an array.
Declaring an array includes the name of the array variable (referred to as the array name) and the type of the array.
Array element type array name [];
Element type of array[] array name;
Array element type array name[][];
Element type of array[][] array name;
For example:
floatboy[];charcat[][];
Then the elements of the array boy are all float type variables and can store float type data. The elements of the array cat are all char type variables and can store char type data.
Multiple arrays can be declared at once, for example:
int[]a,b;
Two int type one-dimensional arrays a and b are declared. The equivalent declaration is:
inta[],b[];
Special attention needs to be paid to:
int[]a,b[];
It declares a one-dimensional array a of type int and a two-dimensional array b of type int. The equivalent declaration is:
inta[],b[][];
Note : Unlike C and C++, Java does not allow you to specify the number of array elements within square brackets in the array declaration. If you declare:
inta[12];
or
int[12]a;
will result in a syntax error.