Generate Random Number in Java in a Range

In this tutorial I will teach you how to generate random number in Java in a range.

There are two ways by which Java random number can be generated. The first way is to use nextInt() method of java.util.Random class and second way is to use random() method of java.lang.Math class.

Below I have shared one example for each.

Generate Random Number in Java in a Range

java.util.Random

The nextInt() method generates random number in a range. Below example will generate random number in between 1 and 10. Here 1 is inclusive and 10 is exclusive.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

packagecom;

importjava.util.Random;

publicclassRandomNumber{

publicstaticvoidmain(Stringargs[]){

Random random=newRandom();

//Generate random number between 1(inclusive) and 10(exclusive)

for(inti=0;i<5;++i){

System.out.println("Random Number in Java: "+random.nextInt(10));

}

}

}

Output

java.lang.Math

The random() method generates a random number in between 0.0 and 1.0. Here 0.0 is inclusive and 1.0 is exclusive. In below example I have multiplied the result with 10 and type casting it into int to get random number in between 1 and 10.

1

2

3

4

5

6

7

8

9

10

11

12

13

packagecom;

publicclassRandomNumber{

publicstaticvoidmain(Stringargs[]){

intrandom;

//Generate random number in between 1(inclusive) and 10(exclusive)

for(inti=0;i<5;++i){

random=(int)(Math.random()*10);

System.out.println("Java Random Number: "+random);

}

}

}

Output

If you found anything incorrect or have any doubts regarding above Java random number tutorial then comment below.