Java

How to Generate Random Numbers in Java

While programming in Java, there can be instances where the developer needs to analyze the statistics based on probability or associate the random numbers within the set range with the defined values to get a predicted outcome that is probable. In such case scenarios, generating random numbers in Java is helpful in fetching multiple values with the help of a precise code.

This article will illustrate the approaches to generate random numbers using Java.

How to Generate Random Numbers Using Java?

To generate random numbers in Java, utilize the following approaches:

Approach 1: Generate Random Numbers in Java Using “Math.random()” Method

The “Math.random()” method returns the random numbers greater than or equal to “0” and less than “1”. This method can be utilized to simply generate the random numbers within the default and specified range, respectively.

Example 1: Generate Random Numbers in Java Automatically

In this example, the “Math.random()” method can be used to generate the random numbers within the default range automatically:

System.out.println("The first random number is: "
+ Math.random());
System.out.println("The second random Number: "
+ Math.random());

 
In the above demonstration, simply apply the “Math.random()” method twice to generate the random numbers in the range of “0” to “<1” and display them.

Output


 

In the above output, it can be observed that the random numbers are generated in accordance with the default range.

Example 2: Generate Random Numbers in Java in a Specified Range

In this particular example, the “Math.random()” method can be used to fetch the random numbers within the specified range:

int start = 10;
int end = 30;          
int b = (int)(Math.random()*(end-start+ 1)+ start);
System.out.println(b);

 
Follow the below steps as given in the above code:

    • Firstly, initialize the integer values in order to generate the random numbers in between this range.
    • After that, associate the “Math.random()” method with the “int” data type to return the resultant random number as an integer.
    • Algorithm:5*(30 – 10 + 1) + 10) = “20.5
    • In the above algo, “5” points to the generated default random number, and the latter computation is done to accumulate the generated random number within the specified range i.e “10<20.5<30”.

Output


 

It can be observed that each time the random number is generated within the specified range.

Approach 2: Generate a Random Number in Java Using “java.util.Random” Class

The “java.util.Random” class can be used to associate different methods and return the corresponding random value. The associated “nextInt()” method takes a parameter bound that should be positive and prompts the corresponding random number. The “nextFloat()” method generates random values in the range of 0.0 and 1.0. Whereas, the “nextBoolean()” method scans the input’s next token into a boolean value and gives that value.

In this approach, these methods can be utilized to generate the random float and random integer within the end range and a random boolean value.

Syntax

public boolean nextInt(integer)

 
In the above syntax, “integer” corresponds to the integer to treat the token as an int value.

public Float nextFloat()

 
The above syntax points to the random float that needs to be generated.

Example

Let’s overview the below-demonstrated code:

Random random = new Random();
int x = random.nextInt(50);
float f=random.nextFloat(50);
boolean m=random.nextBoolean();
System.out.println(x);
System.out.println(f);
System.out.println("The Boolean Value is: "+m);

According to the above code-snippet, apply the following steps:

    • First of all, create a new random object via the “new” keyword and the “Random()” constructor, respectively.
    • In the next step, associate the “nextInt()” method with the created object to generate a random integer within the specified integer as its(method) parameter, i.e., “50”.
    • Likewise, apply the “nextFloat()” method to return the random float within the provided range.
    • Now, apply the “nextBoolean()” method to display the randomly generated boolean value., i.e., “true/false”.
    • Finally, display the corresponding random integer, float, and a boolean value, respectively.

Output


 

Approach 3: Generate a Random Number in Java Using “ThreadLocalRandom” Class

The “ThreadLocalRandom” class is utilized to generate/create a stream of pseudo-random numbers. This approach can also be implemented to return the corresponding random integers, floats, and a boolean value within a given range.

Example

The following example illustrates the stated concept:

int number = ThreadLocalRandom.current().nextInt(0,100);
double floatnum = ThreadLocalRandom.current().nextDouble(0,100);
boolean bool = ThreadLocalRandom.current().nextBoolean();
System.out.println("Randomly Generated Integer Value is: "+number);
System.out.println("Randomly Generated Double Value is: "+floatnum);
System.out.println("Randomly Generated Boolean Value is: "+bool);

 
According to the given code:

    • First, associate the “ThreadLocalRandom” class with the “nextInt()” method to return the randomly generated integer within the given range.
    • After that, repeat the above step for fetching a random double within the provided range and a random boolean value.
    • Lastly, display all the discussed randomly generated values on the console.

Output


 

That was all about generating random numbers in Java.

Conclusion

To generate random numbers in Java, apply the “Math.random()” method, the “java.util.Random” class, or the “ThreadLocalRandom” class. These approaches can be utilized to simply generate a random number within the default range, a random integer, or float within the specified range or a random boolean value, respectively. This blog elaborated on the approaches to generate random numbers using Java.

About the author

Umar Hassan

I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.