Java Language Random Number Generation Pseudo Random Numbers


Java provides, as part of the utils package, a basic pseudo-random number generator, appropriately named Random. This object can be used to generate a pseudo-random value as any of the built-in numerical datatypes (int, float, etc). You can also use it to generate a random Boolean value, or a random array of bytes. An example usage is as follows:

import java.util.Random;  

Random random = new Random();
int randInt = random.nextInt();
long randLong = random.nextLong();

double randDouble = random.nextDouble(); //This returns a value between 0.0 and 1.0
float randFloat = random.nextFloat(); //Same as nextDouble

byte[] randBytes = new byte[16];
random.nextBytes(randBytes); //nextBytes takes a user-supplied byte array, and fills it with random bytes. It returns nothing.

NOTE: This class only produces fairly low-quality pseudo-random numbers, and should never be used to generate random numbers for cryptographic operations or other situations where higher-quality randomness is critical (For that, you would want to use the SecureRandom class, as noted below). An explanation for the distinction between "secure" and "insecure" randomness is beyond the scope of this example.