Java Random - nextBytes() Method
The java.util.Random.nextBytes() method is used to generate random bytes and places them into a user-supplied byte array. The number of random bytes produced is equal to the length of the byte array.
Syntax
public void nextBytes(byte[] bytes)
Parameters
bytes |
Specify the byte array to fill with random bytes. |
Return Value
void type.
Exception
Throws NullPointerException, if the byte array is null.
Example:
In the example below, the java.util.Random.nextBytes() method is used to generate random bytes and places them into a given byte array.
import java.util.*; import java.util.stream.LongStream; public class MyClass { public static void main(String[] args) { //creating a random object Random rand = new Random(); //creating a byte array byte[] Arr = new byte[10]; //place random bytes in the array rand.nextBytes(Arr); //printing the array System.out.println("Arr contains:"); for(byte i: Arr) System.out.println(" " + i); } }
One of the possible outcome is given below:
Arr contains: 101 -81 4 -112 -70 -9 107 30 -18 -86
❮ Java.util - Random