Java & integer Overflow

Does anybody ever wish Java detected & reported integer overflow (via some kind of ArithmeticException) ?

For there to be no compile time, or runtime checking for this fail-slow error seems to me to be a serious limitation in the construction of complex systems.
The simplest assumption that many people fall foul of :-


assert Math.abs(val)>=0;

The above assertion will fail when val = Integer.MIN_VALUE (as it will overflow round to itself)

A very common application of this flawed assertion would be :-

Math.abs(random.nextInt())%range

Which will lead to an erroneous value being generated every 1 in ~4294967296 executions.
While the above is poor code (in both J2ME & J2SE), I have seen many examples of its usage.

Another common situation where overflow becomes a brain melter is when using FixedPoint libraries :-[

If all my code failed one in 4294967296 times, I would be a happy and probably rich man.

PITA, but if you want to be sure…


         int a = ...;
         int b = ...;
         int c = a * b;

         assert ( ((a >>> 31) ^ (b >>> 31)) == (c >>> 31) );

Eh… which works… for ‘quite a few’ cases :slight_smile: (damn double int overflow)