Filling byte array in Java

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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 + " ");
}
raja
Published on 09-Jan-2019 15:56:26
Advertisements