
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
Fill Elements in a Char Array in Java
In this article, we will fill elements in a char array using Java. We will be using the Arrays.fill() method to fill it with a specific character. This method allows us to assign a single character value to all elements in the array. We will fill the array with the character 'A' and then print the array using Arrays.toString() to display its contents in a readable format.
Problem Statement
Write a Java program to fill elements in a char array ?
Input
charValue = 'A'
Output
The char array content is: [A, A, A, A, A]
Steps to fill elements in a char array
Following are the steps to fill elements in a char array ?
- First, we will import the Arrays class from java.util package.
- We will define a char array of size 5.
- We will assign the character 'A' to all elements of the array using the Arrays.fill() method.
- Finally, we will print the contents of the array using Arrays.toString().
Java program to fill elements in a char array
Below is the Java program to fill elements in a char array ?
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]
Code Explanation
In the above program, we create a char array with 5 elements and use the Arrays.fill(charArray, 'A') method to fill each element with the character 'A'. This method efficiently assigns the value to all elements in the array. After filling the array, we use Arrays.toString(charArray) to print the array contents in a formatted string. The output will show that all elements of the array have been filled with the character 'A'.