Home > DeveloperSection > Beginner > Generate random numbers in Java

Ratings:
0 Comment(s)
1376  View(s)
Rate this:

# Generate random numbers in Java

There are two principal means of generating random (really pseudo-random) numbers:

• The Random class generates random integers, doubles, and longs and so on, in various ranges.
• The static method Math.random generates doubles between 0 (inclusive) and 1 (exclusive).

To generate random integers:

• Do not use Math.random (it produces doubles, not integers)
• Use the Random class to generate random integers between 0 and N.

To generate a series of random numbers as a unit, you need to use a single Random object - do not create a new Random object for each new random number.

1)      Using Random class:

`package randomnum; import java.util.Random; public class RandomNum { public static void main(String[] args) {        System.out.println("Generating 10 numbers in between 1 and 100");        Random r = new Random();    for (int i = 1; i <= 10; ++i){      int rno = r.nextInt(100);      System.out.println("Generated : " + rno);}}}    `

OUTPUT:

Generating 10 numbers in between 1 and 100

Generated : 45

Generated : 12

Generated : 1

Generated : 57

Generated : 24

Generated : 84

Generated : 88

Generated : 6

Generated : 93

Generated : 18

The `java.util.Random` class allows you to create objects that produce pseudo-random numbers with uniform or gaussian distributions according to a linear congruential formula with a 48-bit seed.

The nextInt(int n) method is used to get a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

IllegalArgumentException -- This is thrown if n is not positive.

2)      Using Math.random function:

`package randomno;public class RandomNo {    public static void main(String[] args) {System.out.println("Generating 10 numbers in between 1 and 100");int min=1,max=100;for(int i=1;i<=10;i++)     {             int rno = min + (int)(Math.random() * ((max - min) + 1));            System.out.println(rno);     }}} `

OUTPUT:

Generating 10 numbers in between 1 and 100

87

95

45

42

19

74

42

10

71

17