I am trying to generate a random positive 8-bit integer. The documentation for ThreadLocalRandom.current().nextInt(min, max) specifically says that min is the minimum inclusive bound, and max is the maximum exclusive bound. However, if I set max to any value > 128, I will occasionally get a negative value.
This seems to be associated with the bits of an integer, but the documentation says nothing about bits for nextInt(). I really need as many positive 8-bit numbers as I can get. Why is nextInt() returning negative values when I only specify a positive range of (1, 255)?
byte aa = 1;
do {
aa = (byte) ThreadLocalRandom.current().nextInt(1, 128);
} while (aa > 0);
System.out.println(aa);
You cast the result to byte. byte only holds numbers between -128 and 127, and when nextInt returns a larger number than 127, it overflows and rolls over.
This isn't the fault of nextInt, it's the fault of the cast to byte.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With