1

The Math class in Java has a method, Math.random() which returns a pseudorandom number between 0 and 1.
There is also a class java.util.Random which has various methods like nextInt(), nextFloat(), nextDouble(), nextLong()etc.

My question is that if I want to get a random number in a range (say, 30-70), then which way should I go? The factors under consideration are speed and randomness.

dryairship
  • 6,022
  • 4
  • 28
  • 54

3 Answers3

5

If you look at the implementation of Math.random(), you'll see that it uses an instance of the Random class :

public static double random() {
    return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}

private static final class RandomNumberGeneratorHolder {
    static final Random randomNumberGenerator = new Random();
}

Therefore the randomness would be the same.

That said, since you need an int and not a double, you'd better use the nextInt method of the Random class, since it would save you the multiplication and casting of a double to int.

Random rnd = new Random();
int num = rnd.nextInt(41)+30;
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Math.random() does rely on the Random class. Depending on the case and data type you are using you can use either. For an int Random.nextInt() would probably be the best choice.

Speaking of randomness, a more secure random class is SecureRandom. SecureRandom does not rely on the system time unlike Random, so if your application has a security element to it definitely use SecureRandom. Same method names, except

SecureRandom secureRandom = new SecureRandom() instead of

Random random = new Random().

Mario Ishac
  • 5,060
  • 3
  • 21
  • 52
0

I personally would go with the random class, because, in my opinion, it's way easier to use and to influence with parameters, for example for a random number between 30-79

Random r = new Random(); int i = r.nextInt(40)+30;

I hope that helped at least a bit