
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Initialize an Array with Reflection Utilities in Java
An array can be initialized using the method java.util.Arrays.fill() that is a utility method provided in the java.util.Arrays class. This method assigns the required value to all the elements in the array or to all the elements in the specified range.
A program that demonstrates this is given as follows −
Example
import java.util.Arrays; public class Demo { public static void main(String[] arg) { int[] arr = {2, 5, 8, 1, 9}; System.out.print("The array elements are: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } Arrays.fill(arr, 9); System.out.print("\nThe array elements after Arrays.fill() method are: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } } }
Output
The array elements are: 2 5 8 1 9 The array elements after Arrays.fill() method are: 9 9 9 9 9
Now let us understand the above program.
First, the elements of the array arr are printed. A code snippet which demonstrates this is as follows −
int[] arr = {2, 5, 8, 1, 9}; System.out.print("The array elements are: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); }
After this, the Arrays.fill() method is used to assign the value 9 to all the elements in the array arr. Then this array is printed. A code snippet which demonstrates this is as follows −
Arrays.fill(arr, 9); System.out.print("\nThe array elements after Arrays.fill() method are: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); }
Advertisements