Search code examples
javarandomcastingbukkitmodulo

Why is Random.nextInt() %16 skewed while Random.nextInt(16) works perfectly fine?


I am writing a Bukkit plugin that treats snowballs as paintballs. When I accidentally used:

(byte) (random.nextInt() % 16)

instead of

(byte) (random.nextInt(16))

I noticed that lower numbers appeared way more than higher numbers. Why does that happen?

Ex: Before:

00010
01200
06001
30010
00502

Ex: After:

74108
73447
98956
17386
26574

Solution

  • random.nextInt() can also return negative values, and my program was treating negatives as zero, doubling tripling the chance for a zero to occur.