What is the difference between Math.random and java.util.Random?

5

What's the difference in using random without import , right in method.

public class random {

    public static void main(String[] args) {

        int x = (int) (Math.random() * 10);
        System.out.println(x); 

    }

} 

Or with the import in the class, what's the difference?

import java.util.Random;

public class random {

    public static void main(String[] args) {

        Random aleatorio = new Random();
        int numero = aleatorio.nextInt(10);
        System.out.println(numero);

    }

}
    
asked by anonymous 13.02.2016 / 15:14

2 answers

5

The first difference is that Math.random ( ) is a static method of class Math , while java.util.Random is a class.

In this aspect the advantage of Math.random on java.util.Random is that it is not necessary to create an object.

Math.random () returns a double of 0.0 to, but not including 1.0. To achieve another range of values it is necessary to resort to operations such as multiplication. You need to use cast to convert it to an integer.
Internally uses java.util.Random as the number generator.

The java.util.Random class provides more flexible ways to generate evenly distributed random numbers, providing easy generation of types other than double .

One thing that might be interesting (in case of testing) is that if two instances of java.util.Random are created with the same seed, and the same sequence of method calls is made for each one, they will generate and return identical sequences of numbers.

    
13.02.2016 / 15:52
2

The class is more complete and flexible, allows you to determine the type of data you want and is more efficient. It can, for example, repeat the same numbers if used with the same seed.

The static method contained in Math is simpler and resolves without many worries, the method takes care of various details for you, consequently you can not configure how you want to use it. Only works with double values. It is practical when you need the basics.

    
13.02.2016 / 15:35