new Random(x) just creates the Random object with the given seed, it does not ifself yield a random value.
I presume you are asking what the difference is between nextInt() % x and nextInt(x).
The difference is as follows.
nextInt(x)
nextInt(x) yields a random number n where 0 ≤ n < x, evenly distributed.
nextInt() % x
nextInt() % x yields a random number in the full integer range1, and then applies modulo x. The full integer range includes negative numbers, so the result could also be a negative number. With other words, the range is −x < n < x.
Furthermore, the distribution is not even in by far the most cases. nextInt() has 232 possibilities, but, for simplicity's sake, let's assume it has 24 = 16 possibilities, and we choose x not to be 16 or greater. Let's assume that x is 10.
All possibilities are 0, 1, 2, …, 14, 15, 16. After applying the modulo 10, the results are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5. That means that some numbers have a greater likelihood to occur than others. That also means that the change of some numbers occurring twice has increased.
As we see, nextInt() % x has two problems:
- Range is not as required.
- Uneven distribution.
So you should definetely use nextInt(int bound) here. If the requirement is get only unique numbers, you must exclude the numbers already drawn from the number generator. See also Generating Unique Random Numbers in Java.
1 According to the Javadoc.
%has worse statistical properties.nextInt()is actually returningbytevalue. In that case,nextInt()(no arg) returns a number in range-128to127, so ifx = 100,nextInt() % xwill return-99to99, and the numbers between-28and27are twice as likely as the rest. In comparison,nextInt(x)will return0to99, and all the numbers are equally likely. Conclusion: You teacher is dead wrong, the chance to get the same number twice is increased when using%, and the numbers aren't even in the same range.N % n > 0, then anyainNwould more likely be towards the lower end ofa % nrnd = new Random(x);creates a new random number generator object.rnd.nextInt() % x;uses this random number generator. I would not use the % (remainder) operator, but rather use rnd.nextInt(x).