Home >Java >javaTutorial >How to define java integer array
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, [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 choose according to their own programming habits.
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 [ ]. Moreover, for an array defined above, we cannot access any of its elements. We must allocate memory space for it. At this time, we need to use the 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];
Initialization of arrays
You can initialize the array while declaring it (static initialization), or you can initialize it after the declaration (dynamic initialization). For example:
// 静态初始化 // 静态初始化的同时就为数组元素分配空间并赋值 int intArray[] = {1,2,3,4}; String stringArray[] = {"Java", "http://www.java.com", "一切编程语言都是纸老虎"}; // 动态初始化 float floatArray[] = new float[3]; floatArray[0] = 1.0f; floatArray[1] = 132.63f; floatArray[2] = 100F;
Related learning recommendations: java basic tutorial
The above is the detailed content of How to define java integer array. For more information, please follow other related articles on the PHP Chinese website!