2

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);
so8857
  • 351
  • 2
  • 14

1 Answers1

9

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413