Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Arrays.fill()

Fills the whole array or part of it with one value.

Available since: Java 1.2

Syntax

static void fill(int[] a, int val)

Parameters

ParameterTypeDescription
aint[], Object[], …The array to fill. There is a version with a range (fromIndex, toIndex).
valelement typeThe value written to every element.

Return value

voidNothing — the array itself is changed.

Examples

Filling everything and a range:

void main() {
    int[] scores = new int[5];
    Arrays.fill(scores, -1);
    IO.println(Arrays.toString(scores));
 
    char[] line = new char[6];
    Arrays.fill(line, '-');
    Arrays.fill(line, 2, 4, '*');
    IO.println(new String(line));
}

Output:

[-1, -1, -1, -1, -1]
--**--

Notes

For an array of objects every cell gets the same object. Arrays.fill(rows, new int[3]) for a 2D array makes all rows point to one array — changing one changes them all. Fill a 2D array row by row in a loop.

See also

  • Arrays.copyOf() — Copies an array into a new one of the same or another length. copyOfRange() copies a part.
  • array.length — The length of an array — the number of elements. A field, not a method: no parentheses.
  • Arrays.toString() — Returns the contents of an array as a string like [1, 2, 3].

Related recipes

In the tutorial

  • The Arrays class — Utilities of java.util.Arrays: toString, sort, fill, copyOf, copyOfRange, equals and binarySearch.

Thanks for reading!

Donate to the site — we work hard for you.