Java Program to fill elements in a byte array

Java 8Object Oriented ProgrammingProgramming

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));
raja
Published on 09-Jan-2019 16:04:59
Advertisements