How to Generate Random Integers in Java
Generating random numbers using Java is one of the most common question beginners tend to fall upon. However, the task is not at all difficult. Let us look at the three common approaches which are being followed in order to generate a Random Integer.
- java.util.Random
- Math.random
- java.util.concurrent.ThreadLocalRandom
java.util.Random
In order to generate random integers using this class, we need to create an instance of the
class first and then invoke methods such as nextInt(), nextDouble(), etc.
We can generate random numbers of type integers, float, double, long, Boolean using this
class. Let us look at an example to know how that works.
Output
Let us look at the output of the above example code.
Math.random()
The math class contains numerous methods for performing various numeric operations such as
calculating exponential values, logarithms, etc. One of these methods is random(),
which returns a double value in the range of 0.0 to 1.0. But this method can
generate random values of type double only.
Let us look at an example to demonstrate how Math.random() is used to generate
random value.
Output
Let us look at the output of the above example code.
java.util.concurrent.ThreadLocalRandom
This class was introduced way back in Java 1.7 version to generate random numbers of type integer, double, Boolean, etc. Let us look at an example code to generate random numbers of type integers, double and Boolean.
Output
Let us look at the output of the above example code.
Generate Random Number within a Range
In a scenario where the random number being generated is restricted to a certain range we use the following technique.
Output
Let us look at the output of the above example code.
Here, the number generated will always be in between 0 - 49. Basically, we just need to pass the upper limit of the range as the parameter and it will generate a random number between 0 to upper limit – 1.
Summary
Having discussed so many methods and different scenarios of random number generation, now you can manipulate and generate a random number as per your requirement.