As time matter the most in my code so I have asked this. Actually I have to Generate Random Integer (int) in Java Programming language million of times in a loop so only a simple difference is going to work in this case.
I have to generate random number from 1 to 6 as said inside a loop.
First :- java.util.Random class
This is taken from this taken from here.
I have also posted the Screenshot below this.
import java.util.Random;
static Random randGen = new Random();
int spots;
spots = randGen.nextInt(6) + 1;
Second :- Math.random() method
int n = (int)(6.0 * Math.random()) + 1;
Cast is used as this method always returns a floating point value.
As now, I think you are familiar with the things So here is my question which one is the fastest and why? Both uses other classes, Both don't have argument of minimum value like in my case its one. Random class have a argument of largest value But Math.random() Does not have that.
But on the other hand, in order to use Math.random()
we have to use the cast (int) also, as the Random value should be a Integer.