DEV Community

Swapnil Gupta
Swapnil Gupta

Posted on

Arrays.fill in Java

Ever thought how to fill the whole array with same value in Java !?
in CPP, we use memset or can initialise with any value, when it comes to java, we use Arrays.Fill().

Arrays.fill(name of Array, value), it takes the name of array and value

index

we can use form start index to end index to fill the particular value

int ar[] = {2, 2, 2, 2, 2, 2, 2, 2, 2};
  // Fill from index 1 to index 4.
Arrays.fill(ar, 1, 5, 10);
System.out.println(Arrays.toString(ar));
Enter fullscreen mode Exit fullscreen mode

[2, 10, 10, 10, 10, 2, 2, 2, 2]

it is very helpful in Dp or when you want to assign same value.

multiple values

 public static void main(String[] args)
    {
        int [][]ar = new int [3][4];

        // Fill each row with 10. 
        for (int[] row : ar)
            Arrays.fill(row, 10);

        System.out.println(Arrays.deepToString(ar));
    }
Enter fullscreen mode Exit fullscreen mode

we have used Arrays.deepToString() method Printing 2D array.

using stream method

double[][] arr = new double[20][4];
Arrays.stream(arr).forEach(a -> Arrays.fill(a, 0));
Enter fullscreen mode Exit fullscreen mode

3D array

 int[][][] ar = new int[3][4][5];

        // Fill each row with -1. 
        for (int[][] row : ar) {
            for (int[] rowColumn : row) {
                Arrays.fill(rowColumn, -1);
            }
        }

        System.out.println(Arrays.deepToString(ar));
    }
Enter fullscreen mode Exit fullscreen mode

understanding

double[][] arr = new double[5][2];
Arrays.fill(arr[0], 0);
Arrays.fill(arr[1], 0);
Arrays.fill(arr[2], 0);
Arrays.fill(arr[3], 0);
Arrays.fill(arr[4], 0);
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)