Java random numbers FAQ: How do I create random numbers in Java?
To create random numbers in a Java program, use the java.util.Random
class.
As a simple example, this code generates a random number between 0
and 9
:
import java.util.Random; Random random = new Random(); int randomInt = random.nextInt(10);
The 10
inside the nextInt
method tells nextInt
to return a value between 0 (inclusive) and 10 (exclusive), with the result being that the random number you get back will be in the range 0 to 9.
Here’s a Java method that encapsulates how this works:
/** * Returns a value between 0 (inclusive) and the value you supply (exclusive). * So supplying `10` will result in a number between 0 and 9. */ private int getRandomInt(int ceilingExclusive) { Random random = new Random(); return random.nextInt(ceilingExclusive); }
If all you needed to see was how to generate a random integer, I hope that example helps.
Example Java Random number class
For a more complicated demonstration, here’s an example Java class named JavaRandomTests that generates ten random integers whose values range from 0 to 99:
import java.util.Random; public class JavaRandomTests { public static void main(String[] args) { Random random = new Random(); for ( int i=0; i<10; i++ ) { int randomInt = random.nextInt(100); System.out.println( "randomInt = " + randomInt ); } } }
Second Java Random FAQ
Java random question #2: Can I generate other things besides Java int values using this Random class?
Yes, the Java Random
class has other methods like these:
nextBoolean() nextDouble() nextFloat() nextLong()
and more, so you can create other random objects in your Java code.
Summary
I hope these “Java random” examples and source code have been helpful. As you can see, it’s fairly easy to create random numbers in Java.