- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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("
The 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("
The array elements after Arrays.fill() method are: "); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); }
- Related Articles
- How to initialize an array in Java
- Create new instance of an Array with Java Reflection Method
- Create array with Array.newInstance with Java Reflection
- How to initialize an array in Kotlin with values?
- How to initialize an array in JShell in Java 9?
- Reflection Array Class in Java
- How do I declare and initialize an array in Java?
- How to initialize an array using lambda expression in Java?
- Initialize an ArrayList in Java
- How do we initialize an array within object parameters in java?
- How to declare, create, initialize and access an array in Java?
- Use reflection to create, fill, and display an array in Java
- How to initialize an array in C#?
- how to initialize a dynamic array in java?
- How to initialize elements in an array in C#?

Advertisements