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

comments powered by Disqus
Tweet Submit to reddit
© 2006-16 Fabien Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License.