Fill elements in a Java byte array in a specified range

Java 8Object Oriented ProgrammingProgramming

Elements can be filled in a Java byte array in a specified range using the java.util.Arrays.fill() method. This method assigns the required byte value in the specified range to the byte array in Java.

The parameters required for the Arrays.fill() method are the array name, the index of the first element to be filled(inclusive), the index of the last element to be filled(exclusive) 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[10];
      byte byteValue = 2;
      int indexStart = 3;
      int indexFinish = 6;
      Arrays.fill(byteArray, indexStart, indexFinish, byteValue);
      System.out.println("The byte array content is: " + Arrays.toString(byteArray));
   }
}

Output

The byte array content is: [0, 0, 0, 2, 2, 2, 0, 0, 0, 0]

Now let us understand the above program.

First the byte array byteArray[] is defined. Then the the Arrays.fill() method is used to fill the byte array with value 2 from index 3(inclusive) to index 6(exclusive). Finally, the byte array is printed using the Arrays.toString() method. A code snippet which demonstrates this is as follows −

byte[] byteArray = new byte[10];
byte byteValue = 2;
int indexStart = 3;
int indexFinish = 6;
Arrays.fill(byteArray, indexStart, indexFinish, byteValue);
System.out.println("The byte array content is: " + Arrays.toString(byteArray));
raja
Published on 11-Jan-2019 12:11:02
Advertisements