What is the method for defining and initializing arrays…
There are several methods to define and initialize arrays in Java.
- Initialize an array directly: Specify the values of the elements in the array at the time of its declaration. For example:
int[] arr = {1, 2, 3, 4, 5};
- Initialize an array with the new keyword: Creating a new array object with the new keyword and allocating memory space for the array elements. For example:
int[] arr = new int[5];
- Initialize an array using a for loop: By iterating through the array, assign a value to each element of the array. For example:
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
- Initialize an array using the Arrays class: Use methods from the java.util.Arrays class to initialize the array. For example:
int[] arr = new int[5];
Arrays.fill(arr, 0); // 将数组元素都初始化为0
These methods allow for choosing the appropriate way to define and initialize arrays based on specific requirements.