Java Program to fill elements in a byte array


Elements can be filled in a byte array using the java.util.Arrays.fill() method. This method assigns the required byte value to the byte 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 {
      byte[] byteArray = new byte[5];
      byte byteValue = 5;
      Arrays.fill(byteArray, byteValue);
      System.out.println("The byte array content is: " + Arrays.toString(byteArray));
   }
}

Output

The byte array content is: [5, 5, 5, 5, 5]

Now let us understand the above program.

First the byte array byteArray[] is defined. Then the value 5 is filled in the byte array using the Arrays.fill() method. Finally, the byte array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows −

byte[] byteArray = new byte[5];
byte byteValue = 5;
Arrays.fill(byteArray, byteValue);
System.out.println("The byte array content is: " + Arrays.toString(byteArray));

Updated on: 25-Jun-2020

126 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements