Fill Array with Arrays.fill()
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
Array of 5 zeros
Four negative ones
Empty array
Array of 3 sevens
Single element
Algorithm Flow

Solution Approach
Best Answers
import java.util.Arrays;
class Solution {
public int[] solution(int n, int val) {
int[] arr = new int[n];
Arrays.fill(arr, val);
return arr;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
