Monday, June 15, 2009

Java int Overflow Behavior

A coworker recently asked me if there was a guaranteed behavior in the case of int overflow. He gave the specific example on:
can we rely that int x = Integer.MAX_VALUE + 1 is the same for every JVM on any platform?

I thought the answer would be easy to find in the Java specifications document. But I was wrong. It is not clearly defined.

I found a trick that suggests this behavior is indeed standard and will stay the same, it is related to type casting. Java guarantees that the cast of a long just truncates the long to int precision. Therefore if
long l = Integer.MAX_VALUE;
l = l +1;
x = (int)l;
x has a guaranteed value.

http://java.sun.com/docs/books/jls/third_edition/html/conversions.html
paragraph 5.1.3

3 comments :

  1. Its part of the TCK tests. These are the tests a JVM must pass in order to be a compliant Java VM. So the answer is yes this will be true on all compliant JVMs.

    ReplyDelete
  2. See the binarySearch() methods in the Arrays and Collections classes... it handles a possible overflow due to the addition of two ints by an unsigned right shift...

    ReplyDelete