
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to Fill (initialize at once) an Array in Java
All the elements of an array can be initialized at once using methods from the Arrays utility class in Java. One common method used is Arrays.fill(), which can initialize the entire array or a specific portion of it with a single value.
Filling an Array
The Arrays.fill() method is used to initialize all the elements of an array to a specific value. The first use of Arrays.fill() fills the entire array with the value 100. Then, the second use of Arrays.fill() is applied to a specific range of the array (from index 3 to index 6) with the value 50.
Syntax
The following is the syntax for java.util.Arrays.fill() method
public static void fill(object[] a, int fromIndex, int toIndex, object val)
Example 1
This example fill (initialize all the elements of the array in one short) an array by using Array.fill(arrayname,value) method and Array.fill(arrayname, starting index, ending index, value) method of Java Util class
import java.util.*; public class FillTest { public static void main(String args[]) { int array[] = new int[6]; Arrays.fill(array, 100); for (int i = 0, n = array.length; i < n; i++) { System.out.println(array[i]); } System.out.println(); Arrays.fill(array, 3, 6, 50); for (int i = 0, n = array.length; i < n; i++) { System.out.println(array[i]); } } }
Output
100 100 100 100 100 100 100 100 100 50 50 50
Example 2
An integer array is initialized with specific values: 1, 6, 3, 2, 9. After printing the original values, the Arrays.fill() method is used to change all the elements of the array to the value 18. The following is an example of array filling
import java.util.Arrays; public class HelloWorld { public static void main(String[] args) { // initializing int array int arr[] = new int[] {1, 6, 3, 2, 9}; // let us print the values System.out.println("Actual values: "); for (int value : arr) { System.out.println("Value = " + value); } // using fill for placing 18 Arrays.fill(arr, 18); // let us print the values System.out.println("New values after using fill() method: "); for (int value : arr) { System.out.println("Value = " + value); } } }
Output
Actual values: Value = 1 Value = 6 Value = 3 Value = 2 Value = 9 New values after using fill() method: Value = 18 Value = 18 Value = 18 Value = 18 Value = 18 .