Java Program to fill elements in a char array


Elements can be filled in a char array using the java.util.Arrays.fill() method. This method assigns the required char value to the char array in Java. The two parameters required are the array name 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[5];
      char charValue = 'A';
      Arrays.fill(charArray, charValue);
      System.out.println("The char array content is: " + Arrays.toString(charArray));
   }
}

Output

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 value ‘A’ is filled in the char array using the Arrays.fill() method. Finally, the char array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows −

char[] charArray = new char[5];
char charValue = 'A';
Arrays.fill(charArray, charValue);
System.out.println("The char array content is: " + Arrays.toString(charArray));

Updated on: 25-Jun-2020

546 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements