
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
Filling Byte Array in Java
The byte array in Java can be filled by using the method java.util.Arrays.fill(). This method assigns the required byte value to the byte array in Java. The two parameters required for java.util.Arrays.fill() 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
import java.util.Arrays; public class Demo { public static void main(String[] a) { byte arr[] = new byte[] {5, 1, 9, 2, 6}; System.out.print("Byte array elements are: "); for (int num : arr) { System.out.print(num + " "); } Arrays.fill(arr, (byte) 7); System.out.print("\nByte array elements after Arrays.fill() method are: "); for (int num : arr) { System.out.print(num + " "); } } }
Output
Byte array elements are: 5 1 9 2 6 Byte array elements after Arrays.fill() method are: 7 7 7 7 7
Now let us understand the above program.
First, the elements of the byte array arr are printed. A code snippet which demonstrates this is as follows −
byte arr[] = new byte[] {5, 1, 9, 2, 6}; System.out.print("Byte array elements are: "); for (int num : arr) { System.out.print(num + " "); }
After this, the Arrays.fill() method is used to assign the byte value 7 to all the elements in the array. Then this array is printed. A code snippet which demonstrates this is as follows −
Arrays.fill(arr, (byte) 7); System.out.print("\nByte array elements after Arrays.fill() method are: "); for (int num : arr) { System.out.print(num + " "); }
Advertisements