Hehe, curious. I think this is a “deliberate mistake”, so to speak.
The main reason is how the Integer class is written. Basically, parseInt is "optimized" for positive numbers. When he parses the string, he creates the result cumulatively, but is denied. Then he flips the mark of the end result.
Example:
66 = 0x42
understands how:
4*(-1) = -4 -4 * 16 = -64 (hex 4 parsed) -64 - 2 = -66 (hex 2 parsed) return -66 * (-1) = 66
Now look at your example FFFF8000
16*(-1) = -16 (first F parsed) -16*16 = -256 -256 - 16 = -272 (second F parsed) -272 * 16 = -4352 -4352 - 16 = -4368 (third F parsed) -4352 * 16 = -69888 -69888 - 16 = -69904 (forth F parsed) -69904 * 16 = -1118464 -1118464 - 8 = -1118472 (8 parsed) -1118464 * 16 = -17895552 -17895552 - 0 = -17895552 (first 0 parsed) Here it blows up since -17895552 < -Integer.MAX_VALUE / 16 (-134217728). Attempting to execute the next logical step in the chain (-17895552 * 16) would cause an integer overflow error.
Edit (addition): in order for parseInt () to work "sequentially" for -Integer.MAX_VALUE <= n <= Integer.MAX_VALUE, they would have to implement the logic for "rotation" when they reach - Integer.MAX_VALUE in the cumulative result, starting from the maximum end of the integer range and continuing down from there. Why they did not, it would be necessary to ask Josh Bloch or whoever implemented it in the first place. It could just be an optimization.
However
Hex=Integer.toHexString(Integer.MAX_VALUE); System.out.println(Hex); System.out.println(Integer.parseInt(Hex.toUpperCase(), 16));
It works just fine, for this very reason. In the source for Integer you can find this comment.
pap Aug 17 '12 at 13:01 2012-08-17 13:01
source share