Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ThreadLocalRandom.current().nextInt(1, 255); return values outside of the range [1, 254]? [duplicate]

Tags:

java

random

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);
like image 300
so8857 Avatar asked Jan 23 '26 09:01

so8857


1 Answers

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.

like image 64
Louis Wasserman Avatar answered Jan 24 '26 23:01

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!