Q:

Confusing implementation of java.util.Random nextInt(int n)

I am trying to understand how java.util.Random.nextInt(int n) works and despite all the search and even debugging cannot completely understand the implementation.
It is the while loop that causes confusion:
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)
int bits, val;
do {
    bits = next(31);
    val = bits % n;    
} while (bits - val + (n-1) < 0);

I realize this is supposed to address the modulo bias, but struggling to see how.
Question: how can possibly the expression 
bits - val + (n-1)

be negative given that bits value is 31 bit long, i.e. bits is always positive? If bits is positive, val is always less than bits then while condition always stays > 0...

A:

The question has been already addressed in implementation-of-java-util-random-nextint. 
Basically, we have to drop some top-most elements for bits in the range [0..2^31[ because they induce a non-uniform distribution
Mathematically we check :
bits - val + (n-1) >= 2^31

and could have wrote it as is if java had unsigned 32 bits integer arithmetics.

