Java RandomnextBytes Examples

In this tutorial, we will learn about the Java Random.nextBytes() method, and learn how to use this method to generate random bytes in a given byte array, with the help of examples.

nextBytesbyte bytes

Random.nextBytes() generates random bytes and places them into a user-supplied byte array.

Syntax

The syntax of nextBytes() method is

Random.nextBytes(byte[] bytes)

where

Parameter Description
bytes The byte array to fill with random bytes.

Returns

The method returns void.

Example 1 nextBytesbytes

In this example, we will create an object random of Random class type and a an empty byte array of size 10. We will call nextBytes() on this Random object and pass the empty byte array to the method as argument. The method loads this byte array with the randomly generated bytes.

Java Program

import java.util.Random;

public class Example{ 
    public static void main(String[] args) {
    	Random random = new Random();
    	byte[] bytes = new byte[10];
    	random.nextBytes(bytes);
    	System.out.println("Random bytes : ");
    	for(byte b: bytes) {
    		System.out.println(b);
    	}
    }
}

Output

Random bytes : 
-61
91
69
107
-128
-69
-42
107
53
-102

Output may vary, since the bytes are generated randomly.

Example 2 nextBytesbytes bytes null

In this example, we will take a null byte array and pass this as arguemnt to nextBytes(). Since bytes array is null, nextBytes() should throw java.lang.NullPointerException.

Java Program

import java.util.Random;

public class Example{ 
    public static void main(String[] args) {
    	Random random = new Random();
    	byte[] bytes = null;
    	random.nextBytes(bytes);
    	for(byte b: bytes) {
    		System.out.println(b);
    	}
    }
}

Output

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.Random.nextBytes(Unknown Source)
	at Example.main(Example.java:7)

Conclusion

In this Java Tutorial, we have learnt the syntax of Java Random.nextBytes() method, and also learnt how to use this method with the help of examples.