nowucca.com - personal software technology blog

In Java, there is a difference between these calls:

1
2
3
4
5
</p>
<p>Random random = new SecureRandom();</p>
<p>int result = random.nextInt();</p>
<p>int resultBounded = random.nextInt(Integer.MAX_VALUE);</p>
<p>

The first result will range from -Integer.MAX_VALUE+1 to Integer.MAX_VALUE.
The bounded result will range from 0 to Integer.MAX_VALUE (inclusive).

All of this is clearly defined in the Javadoc.

However, when combined with bitwise operators that preserve the sign bit, it is easy to get an infinite loop:

1
2
3
4
5
6
7
8
9
10
11
</p>
<p>    public static int sizeOfEncodedInteger(int value) {<br />
        int contentLength = 0;<br />
        do {<br />
            value &gt;&gt;= 8;<br />
            contentLength++;<br />
        } while (value != 0);<br />
        return contentLength;<br />
    }</p>
<p>    sizeOfEncodedInteger(result); // can infinite loop<br />
    sizeOfEncodedInteger(resultBounded); // cannot infinite loop<br />