Java Reference
In-Depth Information
int i = Integer.MIN_VALUE;
So will this one:
long i = Long.MIN_VALUE;
In case you're familiar with modular arithmetic, it's worth pointing out that this puzzle can be solved
algebraically. Java's
int
arithmetic is actually arithmetic mod 2
32
, so the puzzle requires a nonzero
solution to this linear congruence:
-i (mod 2
32
)
i
Adding
i
to both sides, we get:
0 (mod 2
32
)
2i
The nonzero solution to this congruence is i = 2
31
. Although this value is not representable as an
int
, it is congruent to -2
31
, which is
Integer.MIN_VALUE
.
In summary, Java uses two's-complement arithmetic, which is asymmetric. The signed integral
types (
int
,
long
,
byte
, and
short
) each have one more negative value than positive, which is
always the minimum value representable in the type. Negating
Integer.MIN_VALUE
doesn't change
its value, and the same holds true for
Long.MIN_VALUE
. Negating
Short.MIN_VALUE
and casting the
resulting
int
value back to a
short
returns the original value (
Short.MIN_VALUE
). A similar result
holds for
Byte.MIN_VALUE
. More generally,
watch out for overflow: Like the Wolfman, it's a
killer
.
The lesson for language designers is the same as in
Puzzle 26
. Consider providing linguistic support
for some form of integer arithmetic where overflow does not happen silently.
< Day Day Up >
Search WWH ::
Custom Search