Random nextBytes() method in Java with Examples

The nextBytes() method of Random class places the generated random bytes into an user-supplied byte array.

Syntax:

public void nextBytes(byte[] bytes)  

Parameters: The function accepts a single parameter bytes which is the non-null byte array in which to put the random bytes.

Return Value: This method has no return value.

Exception: The function does not throws any exception.



Program below demonstrates the above mentioned function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// program to demonstrate the
// function java.util.Random.nextBytes()
  
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
  
        // create random object
        Random r = new Random();
  
        // create byte array
        byte[] bytes = new byte[10];
  
        // put the next byte in the array
        r.nextBytes(bytes);
  
        // print random value of array
        System.out.print("Random bytes = [ ");
        for (int i = 0; i < bytes.length; i++) {
            System.out.printf("%d ", bytes[i]);
        }
        System.out.print("]");
    }
}
chevron_right

Output:
Random bytes = [ -90 -126 -75 50 -117 -13 -55 -63 -117 47 ]

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// program to demonstrate the
// function java.util.Random.nextBytes()
  
import java.util.*;
public class GFG {
    public static void main(String[] args)
    {
  
        // create random object
        Random r = new Random();
  
        // create byte array
        byte[] bytes = new byte[15];
  
        // put the next byte in the array
        r.nextBytes(bytes);
  
        // print random value of array
        System.out.print("Random bytes = [ ");
        for (int i = 0; i < bytes.length; i++) {
            System.out.printf("%d ", bytes[i]);
        }
        System.out.print("]");
    }
}
chevron_right

Output:
Random bytes = [ -82 75 -105 41 -34 94 81 10 -107 -46 37 4 -1 100 -119 ]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




Article Tags :
Practice Tags :