# How to generate random numbers in Java

Generating random number is of the very common tasks. s usually there are multiple ways you can generate random numbers in Java. But there are two primary classes which provide this functionality. First is `java.lang.Math`

and another one is `java.util.Random`

. We will see the various examples of random number generation :

**Generating random numbers using java.lang.Math.random() method : **

The primary purpose of Math class is to provide utility methods to perform mathematical operations and it is not specialized for generating random numbers. The random number generate by this class is a double positive value between 0.0 and 1.0. If you want random integer then you can multiple the returned random number with some interger value and cast it to int value. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

**Generating random numbers using java.util.Random: **

java.util.Random is an utility class to generate stream of psedorandom numbers. It has many utility methods to generate random numbers of type `byte`

, `int`

, `boolean`

, `double`

etc. This class is recomonded over Marth.random number as the quality of random numbers would be better.

## Generating random number between range :

There can be a requirement where you need to generate random numbers only between some range.` nextInt(upperBound)`

method of java.util.Random can be used to generate range bounded random numbers.

In the following example will see how to use the various methods of random number generation in java.

import java.util.Random; public class RandomNumberGeneratorExample { public static void main(String[] args) { //Generate random number using Math.random() System.out.println("Math.random() double : "+Math.random() ); //Generate random integer number using Math.random() System.out.println("Math.random() integer : "+ (int)(Math.random()*1000) ); //Create object of type Random Random ran = new Random() ; //generate integer random number System.out.println("int random number : "+ran.nextInt()); //generate double random number System.out.println("double random number : "+ran.nextDouble()); //generate float float number System.out.println("float random number : "+ran.nextFloat()); //generate long random number System.out.println("long random number : "+ran.nextLong()); //generate integer random number System.out.println("range bound int random number : "+ran.nextInt(200)); } }

Math.random() double : 0.46328505500237194 Math.random() integer : 72 int random number : 1635277315 double random number : 0.07248813828405343 float random number : 0.18497723 long random number : 2750093038382099973 range bound int random number : 188