Java Array Initialization: Quick Guide
There are several ways to initialize and assign values to a Java array.
- Utilize static initialization: assigning values to array elements directly when declaring the array, for example:
int[] arr = {1, 2, 3, 4, 5};
- To use dynamic initialization: start by declaring an array, and then use a loop structure to assign values to the array elements, for example:
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
- To assign the same value to all elements in an array, you can use the Arrays.fill() method. For example:
int[] arr = new int[5];
Arrays.fill(arr, 10);
- By utilizing the Arrays.copyOf() method, you can create a copy of an existing array while specifying both the length and values of the new array, for example:
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = Arrays.copyOf(arr1, arr1.length);