Code Logo

Fill Array with Arrays.fill()

Published at25 Jul 2026
Collections Framework Easy 0 views
Like0

Write a Java function that takes a length n and a value, creates an int array of length n, and fills it with the given value using Arrays.fill(), then returns the array.

Arrays.fill() is a static utility method that assigns a value to all elements of an array. For int[], it sets every element to the specified int value. There are overloaded versions for all primitive types (boolean, byte, char, short, int, long, float, double) and for Object arrays.

Arrays.fill() is more efficient than manually looping to assign values because it uses optimized native methods (System.arraycopy or JVM intrinsic) for large arrays. It can also fill a subrange with a two-argument overload: fill(array, fromIndex, toIndex, value).

Time complexity is O(n) where n is the array length. Space complexity is O(n) for the created array. The fill operation is typically implemented as a fast memset-like operation at the JVM level.

Edge cases include zero-length arrays (nothing to fill), negative lengths (throws NegativeArraySizeException), and various array sizes from small to large.

Example Input & Output

Example 1
Input
5,0
Output
[0,0,0,0,0]
Explanation

Array of 5 zeros

Example 2
Input
4,-1
Output
[-1,-1,-1,-1]
Explanation

Four negative ones

Example 3
Input
0,99
Output
[]
Explanation

Empty array

Example 4
Input
3,7
Output
[7,7,7]
Explanation

Array of 3 sevens

Example 5
Input
1,42
Output
[42]
Explanation

Single element

Algorithm Flow

Recommendation Algorithm Flow for Fill Array with Arrays.fill()
Recommendation Algorithm Flow for Fill Array with Arrays.fill()

Solution Approach

import java.util.Arrays;

class Solution {
    public int[] solution(int n, int val) {
        int[] arr = new int[n];
        Arrays.fill(arr, val);
        return arr;
    }
}

Best Answers

java - Approach 1
import java.util.Arrays;

class Solution {
    public int[] solution(int n, int val) {
        int[] arr = new int[n];
        Arrays.fill(arr, val);
        return arr;
    }
}