Arrays are a composite structure provided by most programming languages, and you can consider defining an array if your program requires multiple variables of the same type. The Java language array variable is a variable of reference type and therefore has Java-specific attributes.
In normal Java development , before using a Java array, we initialize the arrays, allocate memory space, assign values to the elements in the array, but must the Java array be initialized? Not initialized, okay?
In fact, the Java array variable is a reference type of variable, not the array object itself, as long as the array variable point to a valid array object, the program can use the array variable, such as the following example:
public class T {
/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Defining and initializing the Nums array
int nums[] = new int[]{3,13,4,6};
Defining a Prices Array variable
int prices[];
Let the prices array point to the array referenced by nums
Prices = Nums;
for (int i=0;i<prices.length;i++) {
System.out.println (Prices[i]);
}
Assigns the third element of the prices array to a value of 100
PRICES[2] = 100;
Accessing the third element of the Nums array will see the array 100
System.out.println (nums[2]);
}
}
As can be seen from the above code, the prices array is not initialized after the prices array has been defined. After you execute int prices[],
Memory allocation of the program
As you can see from the graph, the prices array at this point does not point to any valid memory, does not point to any array objects, and the program cannot use the prices array variable at this time.
When the program executes prices = Nums, the prices variable points to the array referenced by the nums variable, at which point the prices variable and the Nums variable refer to the same array object.
After executing this statement, the prices variable already points to valid memory and an array object of length 4, so the program can use the prices variable properly.
For an array variable, it does not need to be so-called initialization, as long as the array variable points to a valid array object, the program can use the array variable normally.
Therefore, arrays in the Java language are not necessarily initialized or used normally. Java Beginners can try to use the above example of the method, practical operation, deepen the impression. Finally, I hope that the small part of the sharing is helpful to everyone.
Related reading: " some tips for beginners to beginner Java "
Must the Java array be initialized to be used?