java Random nextBytes() Method
Description
The nextBytes(byte[] bytes) method is used to generate random bytes and places them into a user-supplied byte array.
Declaration
Following is the declaration for java.util.Random.nextBytes() method.
public void nextBytes(byte[] bytes)
Parameters
bytes −This is the non-null byte array in which to put the random bytes.
Return Value
NA
Exception
NA
Getting a Random Byte Array Example
The following example shows the usage of Java Random nextBytes() method. Firstly, we've created a Random object and then using nextBytes() we retrieved a random byte array and printed it.
package com.tutorialspoint;
import java.util.Random;
public class RandomDemo {
public static void main( String args[] ) {
// create random object
Random randomNo = new Random();
// create byte array
byte[] nbyte = new byte[30];
// put the next byte in the array
randomNo.nextBytes(nbyte);
// check the value of array
System.out.println("Value of byte array: ");
for (int i = 0; i < nbyte.length; i++) {
System.out.print(" " + nbyte[i] );
}
}
}
Output
Let us compile and run the above program, this will produce the following result.
Value of byte array: 74 -7 25 110 -56 -112 -95 -56 28 27 -59 -52 -64 2 -73 123 100 22 -42 -51 79 -63 -53 4 53 -78 -54 25 -51 -15
Getting a Random Byte Array with a Given Seed Example
The following example shows the usage of Java Random nextBytes() method. Firstly, we've created a Random object with a seed value and then using nextBytes() we retrieved a random byte array and printed it.
package com.tutorialspoint;
import java.util.Random;
public class RandomDemo {
public static void main( String args[] ) {
// create random object
Random randomNo = new Random();
// create byte array
byte[] nbyte = new byte[30];
// put the next byte in the array
randomNo.nextBytes(nbyte);
// check the value of array
System.out.println("Value of byte array: ");
for (int i = 0; i < nbyte.length; i++) {
System.out.print(" " + nbyte[i] );
}
}
}
Output
Let us compile and run the above program, this will produce the following result.
Value of byte array: 97 -11 79 -8 -120 109 -34 -111 113 -84 27 96 -127 118 -115 103 -73 83 110 -82 36 77 36 -72 -22 89 23 83 -111 -93