- HubPages»
- Technology»
- Computers & Software»
- Computer Science & Programming»
- Programming Languages
How to Generate Random Numbers in Java
Java Random Numbers Overview
I will introduce you to random numbers in Java. First I'll give you what you came here for: ready made examples, then I'll go behind the scenes of random number generation in Java. I will go over each method that generates a "random" number in Java. I will explain why the numbers generated are not really random, and how normal distribution is related to random numbers in Java.
So without much delay here is an example that covers every method of
generating a Random number in standard Java (as of this writing JDK and
JRE 6 are in their 22nd update release) installation on Windows (Note that a statement new java.util.Random is used when you call Math.random(), that's why all my examples use use java.util.Random package).
Java Random Numbers Code Sample
package MathRandom_Java; import java.util.Random; public class Java_Math_Random_All { public static void main( String...strings ) { // Create a new instance or object of class Random Random util_Random = new Random(); // Generate a pseudorandom number between 0.0 and 1.0 // (Note: number will in the range of 0.0 to 1.0, but never 1.0) double util_Random_Double = util_Random.nextDouble(); // Returns the next pseudorandom, Gaussian ("normally") distributed // double value with mean 0.0 and standard deviation 1.0 double util_Random_Gaussian = util_Random.nextGaussian(); // Generate a number between 1.40129846432481707e-45 // to 3.40282346638528860e+38 (positive or negative) float util_Random_Float = util_Random.nextFloat(); // Generate a number between -9,223,372,036,854,775,808 // to +9,223,372,036,854,775,807 long util_Random_Long = util_Random.nextLong(); // Generate a number between -2,147,483,648 to 2,147,483,647 int util_Random_Integer = util_Random.nextInt(); // Generate an integer from a specified range (if your pass // in n as a parameter you numbers will range from 0 to n-1) int util_Random_Integer_from_n = util_Random.nextInt(32); // Generate either true or false pseudorandomly boolean util_Random_Bool = util_Random.nextBoolean(); // Create and initialize an array of 5 bytes byte[] bytes = new byte[5]; // Populate the array with 5 randomly generated bytes // Note: byte is a value that ranges from -128 to 127 util_Random.nextBytes( bytes ); // Creates a java.util.Random object and calls // the nextDouble() method double math_Random = Math.random(); // Display all the results from above methods System.out.println( "Math.random() -> " + math_Random ); System.out.println( "nextDouble() ->" + util_Random_Double ); System.out.println( "nextGaussian() -> " + util_Random_Gaussian ); System.out.println( "nextFloat() -> " + util_Random_Float ); System.out.println( "nextLong() -> " + util_Random_Long ); System.out.println( "nextInt() -> " + util_Random_Integer ); System.out.println( "nextInt(n) -> " + util_Random_Integer_from_n ); System.out.println( "nextBoolean() -> " + util_Random_Bool ); System.out.println( "nextBytes(bytes) -> " ); for( int i = 0; i < bytes.length; i++ ) System.out.println( "Byte " + (i+1) + ": " + bytes[i] ); } }
Sample Output
Math.random() -> 0.008014059073862545
nextDouble() -> 0.4017283520137178
nextGaussian() -> -0.5345105808614735
nextFloat() -> 0.6654831
nextLong() -> 982543587599054257
nextInt() -> -502464678
nextInt(n) -> 3
nextBoolean() -> true
nextBytes(bytes) ->
Byte 1: 62
Byte 2: -83
Byte 3: -93
Byte 4: 114
Byte 5: -109
Java Books
nextInt
First notice that depending on your needs, all you may be looking for
is generating a simple random integer in the range of your choosing.
For that purpose I recommend that you use nextInt(int n) method. Just
remember that if you want to generate numbers from 0 to n pass a number
that is equal n + 1.
For example if I want to generate numbers in the range of 0 to 32 I would pass 33 like so: nextInt(33)
And if I wanted to limit my lower range, I would add a number to what I
generate from nextInt(int n), and subtract the same number from n. For
example nextInt(33-10)+10 would generate numbers in the range of 10 to
32.
nextInt Code Sample
package MathRandom_Java; import java.util.Random; public class Java_Math_Random_Int { public static void main( String...strings ) { // Create a new instance or object of class Random Random util_Random = new Random(); // Generate an integer from a specified range (if your pass // in n as a parameter your numbers will range from 0 to n-1) int pseudorandom_Integer = util_Random.nextInt(32+1); System.out.println( "nextInt( n ) -> " + pseudorandom_Integer ); // Generate an integer from 10 inclusive to 32 exclusive. pseudorandom_Integer = util_Random.nextInt(33-10) + 10; System.out.println( "nextInt( n-10 ) + 10 -> " + pseudorandom_Integer ); } }
Sample Output
nextInt( n ) -> 27
nextInt( n-10 ) + 10 -> 16
Java Random is Not Random
Generating a random number on a computer is not random at all. There is
an algorithm that takes number of milliseconds that have passed
starting from UNIX epoch. Since the number of milliseconds always
changes, a number generated from the numerous random methods in Java,
seems to be random.
If you were to manually pass in the number
of milliseconds (a seed value) to the Random class instance or object,
you would see that every time you generate a "random" value you get the
same result! Run this code repeatedly to see what I mean:
package MathRandom_Java; import java.util.Random; public class Java_Math_Random_Seed { public static void main( String...strings ) { // Create a new instance or object of class Random Random util_Random = new Random(); // If you manually set the seed for your Random object, // the value generated will be the same on each run. util_Random.setSeed( 555 ); // Generate a pseudo random number between 0.0 and 1.0 // (Note: number will be in the range of 0.0 to 1.0, // but never 1.0) double util_Random_Double = util_Random.nextDouble(); System.out.println( "nextDouble() ->" + util_Random_Double ); } }
Sample Output - The Same on All Computers
nextDouble() ->0.6816084544091354
Uniform vs Normal Distributions in Java Random Methods
Another point to consider is that almost all random methods in Java use
uniform distribution method for the their values. Which in plain English means that the probability to select a pseudo random number from
all the possible random numbers that a computer can produce is going to
be the same.
The exception to this rule is the method called
nextGausian() which generates a pseudo random number based on normal
distribution. Translation into simpler language yields: values
generated from nextGausian() are biased toward the most probable, and
he most probably is 0. For example 0.5 is much much more probable to
appear to be generated from nextGaussian() than say 0.0005.
Normal Distribution Blurb
It forms a bell shaped curve, which is also called a normal curve.
Almost everything in nature (including human behavior, like watching
TV) occurs according to this normal curve (if measured and graphed).
The normal curve could by itself take up a lot of volumes of writing
and is not going to be covered in this article, so suffice it to say
that if you wanted to make an application that would simulate a Natural
behavior you would use nextGaussian() method.
Last Words
To sum it all up, there three basic things you have to be aware of when generating pseudo random values:
- Most methods use uniform distribution, but there is one method that uses normal or Gaussian distribution called nextGaussian().
- If you simply want to generate a pseudo random range of positive integers from zero to some number n then use nextInt( n+1 ).
- Alternatively if you want to generate a pseudo random range of positive integers from some number m to some number n, then use nextInt(n-m)+m, given that m is less than n.