Random nextBytes(byte[]) in Java

nextBytes(byte[]): This method is available in java.util.Random class of Java.

Syntax:

void java.util.Random.nextBytes(byte[] bytes)

This method takes one argument. This method generates random bytes and places them into a user-supplied byte array.

Note: The number of random bytes produced is equal to the length of the byte array.

Parameters: One parameter is required for this method.

bytes: the byte array to fill with random bytes.

Throws:

NullPointerException - if the byte array is null.

Approach 1: When no exception

Java

import java.util.Random;

public class RandomnextBytes {
    public static void main(String[] args) {

        Random random = new Random();

        byte[] bytes = { 1, 2, 3, 4 };
        random.nextBytes(bytes);
        System.out.println(random.hashCode());
    }
}

Output:

1130478920


Approach 2: NullPointerException

Java

import java.util.Random;

public class RandomnextBytes {
    public static void main(String[] args) {

        Random random = new Random();

        byte[] bytes = null;
        random.nextBytes(bytes);
        System.out.println(random.hashCode());
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException: Cannot read the array length because "bytes" is null at java.base/java.util.Random.nextBytes(Random.java:228)


No comments:

Post a Comment