Java How To Generate A Random Number
The Java language provides a few different methods to generate random numbers. We’re going to cover these here.
Using the Random Class
Here are some of the methods from the Random class that can be used to generate random numbers.
nextInt() | random integer between 0 and the specified upper bound |
nextDouble() | random double between 0.0 and 1.0 |
nextFloat() | random double between 0.0 and 1.0 |
The method nextInt takes an integer argument specifying the upper bound. It will return an integer somewhere between zero and the upper bound. The method nextDouble() generates and returns a random double between 0.0 and 1.0. The method nextFloat() does basically the same thing except that it returns a float.
Here is an example showing how you can use these.
import java.util.Random;
class Test1 {
public static void main( String args[] ) {
Random rand = new Random();
int ub = 25; // values 0-24
int x = rand.nextInt(ub); // values 0-24
double y = rand.nextDouble(); // 0.0 - 1.0
float z = rand.nextFloat(); // 0.0 - 1.0
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
}
Using the Math Class
You can use the Math.random() method to generate a random double. You can also combine this with the floor function as a roundabout way of generating a random int. I wouldn’t do this though. I would probably just use the Random class.
Math.random() | return positive double between 0.0 and 1.0 |
Math.floor() | return largest double less than or equal to arg and is an integer |
Here is an example.
class Test1 {
public static void main( String args[] ) {
int a = (int)Math.floor(Math.random()*50);
double b = Math.random();
System.out.println(a);
System.out.println(b);
}
}
Using the ThreadLocalRandom Class
It is relatively easy to generate random numbers using the ThreadLocalRandom class. Here is an example showing how you might do that.
import java.util.concurrent.ThreadLocalRandom;
class Test1 {
public static void main( String args[] ) {
int a = ThreadLocalRandom.current().nextInt();
double b = ThreadLocalRandom.current().nextDouble();
System.out.println(a);
System.out.println(b);
}
}