How to Fill Array in Java: Syntax and Examples
In Java, you can fill an array by assigning values in a loop or using
Arrays.fill() to set all elements to the same value. For different values, use a for loop to assign each element individually.Syntax
There are two common ways to fill an array in Java:
- Using a for loop: Assign values to each element by index.
- Using Arrays.fill(): Set all elements to the same value quickly.
java
int[] arr = new int[5]; // Using for loop for (int i = 0; i < arr.length; i++) { arr[i] = i * 2; } // Using Arrays.fill() java.util.Arrays.fill(arr, 10);
Example
This example shows how to fill an array with different values using a for loop and how to fill all elements with the same value using Arrays.fill().
java
import java.util.Arrays; public class FillArrayExample { public static void main(String[] args) { int[] numbers = new int[5]; // Fill with different values for (int i = 0; i < numbers.length; i++) { numbers[i] = i + 1; } System.out.println("Array after for loop: " + Arrays.toString(numbers)); // Fill all elements with the same value Arrays.fill(numbers, 7); System.out.println("Array after Arrays.fill(): " + Arrays.toString(numbers)); } }
Output
Array after for loop: [1, 2, 3, 4, 5]
Array after Arrays.fill(): [7, 7, 7, 7, 7]
Common Pitfalls
Common mistakes when filling arrays include:
- Forgetting to initialize the array before filling it.
- Using
Arrays.fill()when you want different values for each element. - Accessing indexes outside the array bounds in a loop.
Always ensure the array is created with a size before filling it, and use the right method for your needs.
java
int[] arr; // Wrong: arr not initialized // Arrays.fill(arr, 5); // This causes NullPointerException // Correct: arr = new int[3]; java.util.Arrays.fill(arr, 5);
Quick Reference
| Method | Description | Usage Example |
|---|---|---|
| for loop | Fill array with different values | for (int i=0; i |
| Arrays.fill() | Fill array with the same value | Arrays.fill(arr, 10); |
| Initialization | Create array before filling | int[] arr = new int[5]; |
Key Takeaways
Use a for loop to assign different values to each array element.
Use Arrays.fill() to quickly set all elements to the same value.
Always initialize the array with a size before filling it.
Avoid accessing indexes outside the array bounds to prevent errors.
Choose the filling method based on whether values are uniform or varied.