Java Random Number Generator

Random numbers may be required for sorts of programming jobs. For example, statistical sampling, computer simulation, cryptography, and other areas where producing random unpredictable results is desirable.

Java provides certain ways in which we can generate random numbers. Although, the generated random numbers are pseudo-random, they get the work done mostly. We can generate random numbers in Java using the following two ways.

Java Random Number Generator

Method 1: lang.Math

To generate random numbers, we can use the Math.random() method. This method returns a random double value that is greater than 0.0 and less than 1.0.

Output:

The Random number generated is: 0.5932537283492374

There would be a different output each time you run this program.

Generate Random Number in a Range:

To generate a random integer instead, in a given range the following can be done.

Output:

The Random number generated is: 7.0

This would print a different number between 5 to 10, every time we run the program.

Method 2: util.Random

This is the main class for Random number generation in Java. Even the Math.random() method, under the hood, uses the java.util.Random pseudo-random number generator object.

Now to generate random numbers, we first have to create an instance of the Random class, and then call one of its random number generator methods like nextInt(), nextDouble(), or nextLong().

Output:

The Random number generated is: -690646604

A random integer is generated every time the program runs.

To generate a random number less than a given number.

Use random.nextInt(UpperBound)

This would generate random numbers less than the UpperBound.

To generate random numbers between a given range, min and max.

Use random.nextInt((max-min)+1) + min;

This would generate random numbers in the range min and max.