Arrays.fill() in Java with Examples

 In Java, there is a method called "Arrays.fill()" in the "java.util.Arrays" class. This method allows you to assign a specific value to each element of an array.

The syntax of this method is as follows:

  • To fill the entire array with a specific value: "Arrays.fill(int[] a, int val)"
  • To fill a specific range of an array with a specific value: "Arrays.fill(int[] a, int from_Index, int to_Index, int val)"

This method doesn't return any value, it just modifies the array.

There are two exceptions that this method can throw:

  • "IllegalArgumentException" if "from_Index" is greater than "to_Index"
  • "ArrayIndexOutOfBoundsException" if "from_Index" or "to_Index" are out of the bounds of the array.

Here are some examples of how to use this method:

Example 1: Fill an entire array with a specific value.

java
int[] arr = {2, 2, 1, 8, 3, 2, 2, 4, 2}; Arrays.fill(arr, 10); System.out.println("Array completely filled with 10: " + Arrays.toString(arr));

Output:

javascript
Array completely filled with 10: [10, 10, 10, 10, 10, 10, 10, 10, 10]

Example 2: Fill a specific range of an array with a specific value.

java
int[] arr = {2, 2, 2, 2, 2, 2, 2, 2, 2}; Arrays.fill(arr, 1, 5, 10); System.out.println("Filled from index 1 to index 4 with 10: " + Arrays.toString(arr));

Output:

vbnet
Filled from index 1 to index 4 with 10: [2, 10, 10, 10, 10, 2, 2, 2, 2]

Example 3: Fill a multidimensional array with a specific value using a loop.

java
int[][] arr = new int[3][4]; for (int[] row : arr) { Arrays.fill(row, 10); } System.out.println(Arrays.deepToString(arr));

Output:

lua
[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]

You can also fill a 3D array using nested loops in a similar way.

Previous Post Next Post