Java Array Assignment Methods Explained

  1. Iterate through the array in a loop and assign values one by one.
int[] arr = new int[5];
for (int i = 0; i < arr.length; i++) {
    arr[i] = i + 1;
}
  1. Initialize using static initialization:
int[] arr = {1, 2, 3, 4, 5};
  1. Assigning the same value using the Arrays.fill() method.
int[] arr = new int[5];
Arrays.fill(arr, 0);
  1. Copy an array using the System.arraycopy() method.
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = new int[arr1.length];
System.arraycopy(arr1, 0, arr2, 0, arr1.length);
bannerAds