Reputation: 234725
Consider:
long n = Long.MAX_VALUE;
++n;
With my JVM, this wraps round to Long.MIN_VALUE
. Is this the defined behaviour? Will some JVMs throw an exception instead?
Upvotes: 0
Views: 116
Reputation: 41955
JLS: Primitive Types and Values quotes that
The integer operators do not indicate overflow or underflow in any way.
So as the arithmetic types in Java are signed, adding 1 to Long.MAX_VALUE
causes overflow and it goes to Long.MIN_VALUE
as Java uses 2's complement
As the JLS quotes all the integer operators such as ++
will silently overflow the value and not cause any exception
Upvotes: 1
Reputation: 5067
As pointed out in the JLS :
The integer operators do not indicate overflow or underflow in any way.
An integer operator can throw an exception (§11) for the following reasons:
Any integer operator can throw a NullPointerException if unboxing conversion (§5.1.8) of a null reference is required.
The integer divide operator / (§15.17.2) and the integer remainder operator % (§15.17.3) can throw an ArithmeticException if the right-hand operand is zero.
The increment and decrement operators ++ (§15.14.2, §15.15.1) and -- (§15.14.3, §15.15.2) can throw an OutOfMemoryError if boxing conversion (§5.1.7) is required and there is not sufficient memory available to perform the conversion.
and addition(as pointed out by Svetelin Zarev):
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.
I think it is safe to assume that no exception will be thrown in this case and everytime it will overflow to Long.MIN_VALUE
.
Upvotes: 0
Reputation: 6887
Long.MAX_VALUE 9223372036854775807 = +(2^63-1) :
01111111.11111111.11111111.11111111.11111111.11111111.11111111.11111111
++n will increment this binary number and so the sign bit will be used:
Long.MIN_VALUE -9223372036854775808 = -(2^63) :
10000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000
thats not the behaviour of the jvm, thats the behaviour of an icrementation of an binary number.
Upvotes: 2
Reputation: 15683
From the JLS:
If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.
Source: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.18.2
Upvotes: 3