Java - How to generate a random number

In Java you can generate a random number (random number) using:

  • Math.random()
  • Random
  • Apache commons-math3 library

Usually, you can use Math.random() and Random, and if necessary, you can use the commons-math3 library.

Generate random numbers with Math.random()

Math.random() is a static method, which returns a random double that is greater than or equal to 0 and less than 1.

// Math.java
public static double random()

Calling 5 times as follows will return a different number.

for (int i = 0; i < 5; i++) {
    System.out.println(Math.random());
}

Output:

0.18483327372551328
0.4999614694230884
0.2758430606141382
0.8476940006649069
0.8567665839943789

If you want to set the range of randomly generated numbers, you can implement it as follows.

The following code randomly returns a number between 10 and 100.

double min = 10;
double max = 100;
double random = (int) ((Math.random() * (max - min)) + min);
System.out.println(random);

Output:

17.0

If you want to get an int rather than a double, you can cast it as follows.

int min = 10;
int max = 100;
int random = (int) ((Math.random() * (max - min)) + min);
System.out.println(random);

Output:

32

Generate random numbers with Random

java.util.Random is a class used to generate random numbers.

Random can be created like this:

Random random = new Random();

And when nextInt() is called, a random number of type Int is generated. In the range of numbers, any Integer that can be expressed in 32 bits can be returned.

Random random = new Random();
System.out.println(random.nextInt());
System.out.println(random.nextInt());
System.out.println(random.nextInt());
System.out.println(random.nextInt());

Output:

549303722
1433650828
1294409735
1717699611

If you want to generate only random numbers less than a certain number, you can pass the boundary value as an argument as follows.

int bound = 100;
System.out.println(random.nextInt(bound));
System.out.println(random.nextInt(bound));

Output:

46
99

Generate random numbers for Double, Float, and Boolean

In addition to nextInt(), you can generate random numbers for other data types.

  • nextDouble() : Double random number between 0 and 1.
  • nextFloat() : Float random number between 0 and 1.
  • nextLong() : Random number of Long type
  • nextBoolean() : Randomly returns True or False

What is Random Seed?

In fact, Java does not randomly generate random numbers. It is to sequentially calculate numbers according to some algorithm and return the value as a random number.

Actually using Random doesn`t give you the same number. The reason is that when creating a Random object, the initial value is different each time, so the pattern for generating random numbers is different. The initial value referred to here is called seed.

The constructor of the Random class receives a seed as an argument. If you input the same seed, it will always generate a random number with the same pattern.

// Random.java
public Random(long seed)

If you look at the code below, the same seed was entered when creating two Random objects. If you look at the generated random number, you can see that the same random number is generated. Over time, this pattern generates random numbers.

Random random1 = new Random(10);
Random random2 = new Random(10);

System.out.println("r1 : " + random1.nextInt());
System.out.println("r2 : " + random2.nextInt());

Output:

r1 : -1157793070
r2 : -1157793070

In the above example, an object was created with new Random(). And if you look at the random number generated by the object created in this way, you can see that it generates a random number of a different pattern each time it is executed.

The reason is that Random() is implemented to change the seed according to time as follows.

public Random() {
    this(seedUniquifier() ^ System.nanoTime());
}

public Random(long seed) {
    if (getClass() == Random.class)
        this.seed = new AtomicLong(initialScramble(seed));
    else {
        // subclass might have overriden setSeed
        this.seed = new AtomicLong();
        setSeed(seed);
    }
}

So, generating random numbers with new Random() will result in very little overlap.

Generate random numbers using Apache commons-math3 library

You can generate random numbers using commons-math3 library.

To use the library in the Gradle project, add the following to dependencies of build.gradle.

dependencies {
  compile group: 'org.apache.commons', name: 'commons-math3', version: '3.6.1'
  ...
}

You can generate a random number for an int like this:

int randomInt = new RandomDataGenerator().getRandomGenerator().nextInt();

To specify a range, you can do something like this: The following code randomly generates a number between leftLimit and rightLimit.

int leftLimit = 100;
int rightLimit = 120;
int randomInt = new RandomDataGenerator().nextInt(leftLimit, rightLimit);
System.out.println(randomInt);

Output:

112

A random number for a Double can be generated as follows:

double randomDouble = new RandomDataGenerator().getRandomGenerator().nextDouble();

To specify a range, you can do something like this:

double leftLimit = 1D;
double rightLimit = 100D;
double randomDouble = new RandomDataGenerator().nextUniform(leftLimit, rightLimit);

For Long, you can generate random numbers or specify a range like this:

long randomeLong = new RandomDataGenerator().getRandomGenerator().nextLong();

int leftLimit = 100;
int rightLimit = 120;
randomeLong = new RandomDataGenerator().nextLong(leftLimit, rightLimit);
codechachaCopyright ©2019 codechacha