Fill elements in a Java char array in a specified range

Java 8Object Oriented ProgrammingProgramming

Elements can be filled in a Java char array in a specified range using the java.util.Arrays.fill() method. This method assigns the required char value in the specified range to the char array in Java.

The parameters required for the Arrays.fill() method are the array name, the index of the first element to be filled(inclusive), the index of the last element to be filled(exclusive) and the value that is to be stored in the array elements.

A program that demonstrates this is given as follows

Example

 Live Demo

import java.util.Arrays;
public class Demo {
   public static void main(String[] argv) throws Exception {
      char[] charArray = new char[10];
      char charValue = 'A';
      int indexStart = 2;
      int indexFinish = 7;
      Arrays.fill(charArray, indexStart, indexFinish, charValue);
      System.out.println("The char array content is: " + Arrays.toString(charArray));
   }
}

The output of the above program is as follows

The char array content is: [, , A, A, A, A, A, , , ]

Now let us understand the above program.

First, the char array charArray[] is defined. Then the Arrays.fill() method is used to fill the char array with value ‘A’ from index 2(inclusive) to index 7(exclusive). Finally, the char array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows

char[] charArray = new char[10];
char charValue = 'A';
int indexStart = 2;
int indexFinish = 7;
Arrays.fill(charArray, indexStart, indexFinish, charValue);
System.out.println("The char array content is: " + Arrays.toString(charArray));
raja
Published on 17-Jan-2019 14:50:31
Advertisements