Arrays.fill
- Java course
- Beginner
- Lesson 63/116
- 4 min
Learn to fill arrays with Arrays.fill.
Filling arrays: Arrays.fill
To fill every slot of an array with the same value you use Arrays.fill. This is very practical for setting initial values.
int[] board = new int[5];
Arrays.fill(board, 0);
// board: {0, 0, 0, 0, 0}The first parameter is the array, the second is the value. The method changes the array in place; it does not return a new array. It is ideal for resetting game boards, counters or flag arrays.
Filling a portion of the array
Arrays.fill is overloaded: you can pass start and end indices to fill only part of the array. The end index is exclusive.
int[] row = new int[5];
Arrays.fill(row, 1, 4, 9);
// row: {0, 9, 9, 9, 0}Indices 1, 2, 3 become 9; indices 0 and 4 stay untouched. This is handy for tasks like marking the middle of a row.
Practice Reset the score board
Create an int[] array of 5 elements, set every slot to -1 with Arrays.fill, then print the array using Arrays.toString.
Starter code
public class Main {
public static void main(String[] args) {
// Create an int array of 5 elements
// Set every slot to -1
// Print the array
}
}Sample solution
int[] board = new int[5];
Arrays.fill(board, -1);
System.out.println(Arrays.toString(board));Expected output
[-1, -1, -1, -1, -1]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match scenario to method
| Term | Meaning |
|---|---|
Sort the array |
Arrays.sort |
Convert the array to text |
Arrays.toString |
Same value to all slots |
Arrays.fill |
Take a new copy |
Arrays.copyOf |
2 What does Arrays.fill return?
- It returns the first element
- It returns a new filled array
- It returns the number of filled slots
- void; it modifies the array in place Correct answer
Explanation: fill is a void method; it fills the array in place.
3 Fill in the blank: set all slots to 1
int[] flags = new int[4];
Arrays.____(flags, 1);
int[] flags = new int[4];
Arrays.fill(flags, 1);
Explanation: Arrays.fill(flags, 1) sets all flags to 1.