Course contentsShow
← Java
Lesson 272 of 2,8706. ArraysFree lesson

Arrays.fill: Populating Arrays with Values

Setting all elements or a range of elements to a specific value using fill.

Arrays.fill: Populating Arrays with Values

What you'll learn: How to quickly set all elements or a range of elements in an array to the same value using Arrays.fill.

The Problem: Initializing Array Elements

After creating an array with new, you know it gets default values (0 for numbers, false for booleans, null for objects). But what if you need all elements to have a specific value, like 10 or -1? You could write a loop to assign each element individually, but there's a better way.

Using Arrays.fill

The Arrays.fill method from the java.util.Arrays class lets you populate an entire array—or just a portion of it—with a specific value in a single method call.

Basic syntax:

Arrays.fill(array, value);

This sets every element in the array to the given value.

Example:

int[] scores = new int[5];
Arrays.fill(scores, 100);
// scores is now [100, 100, 100, 100, 100]

Filling a Range

You can also fill only a specific range by providing start and end indices:

Arrays.fill(array, fromIndex, toIndex, value);

The fromIndex is inclusive, toIndex is exclusive (just like loop bounds you're used to).

Example:

int[] numbers = new int[6];
Arrays.fill(numbers, 1, 4, 99);
// numbers is now [0, 99, 99, 99, 0, 0]

Think of It Like...

Imagine filling water bottles on an assembly line. Instead of filling each bottle one-by-one manually, you have a machine that fills all bottles (or bottles 5–10) with the same liquid automatically.

Key Takeaway: Use Arrays.fill(array, value) to quickly set all elements to the same value, or Arrays.fill(array, start, end, value) to fill only a specific range—much cleaner than writing manual loops.