Just to add to Greg's reply, if you don't understand a line of code, break it down:
++freq[1 + rand.nextInt(4)];
Becomes
int index = 1 + rand.nextInt(4);
++freq[index];
Becomes
int randomValue = rand.nextInt(4);int index = 1 + randomValue;
freq[index] += 1;
Becomes
int randomValue = rand.nextInt(4);
int index = 1 + randomValue;
freq[index] = freq[index] + 1;
Now it's obvious:
Generate a random number that fits in the array
Add one to it.
Add one to that element of the array.
However, that bad code: although
rand.nextInt(n)
returns a value between
0
and
(n - 1)
inclusive (See the documentation:
Java.util.Random.nextInt() in Java - GeeksforGeeks[
^]) adding one to it means it only uses elements 1, 2, 3, and 4 of the array - the value in index 0 will always be zero.
A better solution would be:
++freq[rand.nextInt(freq.length)];
As that will generate values that can be any index in the array, regardless of the size of teh array.