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

Asked

Viewed 4,930 times

5

What’s the difference in using the random without the import, right in the 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);

    }

}

2 answers

5


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

In this respect the advantage of Math. about java.util. it is not necessary to create an object.

Math.() returns a double from 0,0 to, but not including, 1.0. To achieve another range of values it is necessary to use operations such as multiplication.
Recourse must be had to cast to convert it to an integer number.
Internally uses java.util. as generator of numbers.

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

One aspect that can be interesting (in case of tests) is that if two instances of java.util. are bred with the same seed(Seed), and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers.

2

The class is more complete and flexible, allows 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 solves without many worries, the method takes care of various details for you, consequently you can not configure how you want to use. Only works with values double. He’s practical when he needs the basics.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.