Random number generator in java

Let’s learn random number generator in java.

Random number generator in java

Let’s learn how to generate random numbers in java using some built in methods and classes.

Math.random() method in java

Random function in java returns pseudo random double greater than or equal to 0.0 and less than 1.0. Math.random() method uses Random class internally. Let’s see an example on Math.random() method in java.

```public class RandomMethodExample
{
public static void main(String[] args)
{
// here we are generating random doubles
System.out.println(Math.random());
System.out.println(Math.random());
}
}
```

Output:

0.31834412935584566
0.40181643543705636

java.util.random example

In the below java program we are creating random class java to create random numbers. Then instance methods of Random class namely nextint(), nextFloat(), nextBoolean() methods etc., are invoked.

```import java.util.Random;
public class JavaRandomClass
{
public static void main(String[] args)
{
Random random = new Random();
// random integers in range 0 to 999
int randInt1 = random.nextInt(1000);
int randInt2 = random.nextInt(1000);
// printing random integers
System.out.println("Random Integers: " + randInt1);
System.out.println("Random Integers: " + randInt2);
// here we are generating Random doubles
double randDou1 = random.nextDouble();
double randDou2 = random.nextDouble();
// printing random doubles
System.out.println("Random Doubles: " + randDou1);
System.out.println("Random Doubles: " + randDou2);
}
}
```

Output:

Random Integers: 42
Random Integers: 30
Random Doubles: 0.42230252771804866
Random Doubles: 0.9215482578893138

ThreadLocalRandom class was introduced in java since 1.7. Now let’s see how to generate random numbers in java of data type boolean, double and integer.

```import java.util.concurrent.ThreadLocalRandom;
{
public static void main(String[] args)
{
// generating random integers between 0 to 999
// display random integers
System.out.println("Random Integer: " + randInt1);
// generating random doubles
// display random doubles
System.out.println("Random Double: " + randDou1);
// generating random booleans
// display random booleans
System.out.println("Random Boolean: " + randBool1);
}
}
```

Output:

Random number integer: -1724832069

Random number double: 0.3748088566976404

Random boolean: false

Also read – abstraction in java