# How to Generate Random Number in Java

In Java programming, we often required to generate random numbers while we develop applications. Many applications have the feature to generate numbers randomly, such as to verify the user many applications use the OTP. The best example of random numbers is dice. Because when we throw it, we get a random number between 1 to 6.

## Random Number

Random numbers are the numbers that use a large set of numbers and selects a number using the mathematical algorithm. It satisfies the following two conditions:

• The generated values uniformly distributed over a definite interval.
• It is impossible to guess the future value based on current and past values.

## Generating Random Number in Java

In Java, there is three-way to generate random numbers using the method and classes.

• Using the random() Method
• Using the Random Class
• Using the ThreadLocalRandom Class
• Using the ints() Method (in Java 8)

### Using the Math.random() Method

The Java Math class has many methods for different mathematical operations. One of them is the random() method. It is a static method of the Math class. We can invoke it directly. It generates only double type random number greater than or equal to 0.0 and less than 1.0. Before using the random() method, we must import the java.lang.Math class.

Syntax:

1. public static double random()

It does not accept any parameter. It returns a pseudorandom double that is greater than or equal to 0.0 and less than 1.0.

Let's create a program that generates random numbers using the random() method.

``````import java.lang.Math;
public class RandomNumberExample1
{
public static void main(String args[])
{
// Generating random numbers
System.out.println("1st Random Number: " + Math.random());
System.out.println("2nd Random Number: " + Math.random());
System.out.println("3rd Random Number: " + Math.random());
System.out.println("4th Random Number: " + Math.random());
}
}``````

OutPut Will Be:

```1st Random Number: 0.17434160924512265
2nd Random Number: 0.4297410090709448
3rd Random Number: 0.4828656381344487
4th Random Number: 0.13267917059488898```