long a2 = 100L * 1024 * 1024 * 1024;
In this operation however at least one operand is long
. hence the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long
. The other non-long operand are
widened to type long
by numeric promotion and resulted value gets stored to to variable a2
.
long a1 = 100 * 1024 * 1024 * 1024;
The constant expression of plain integer, the result of the expression was computed as a type int
. The computed value however too large to fit in an integer and hence overflowed, resulting in 0
and gets stored to a1
variable.
Edit: As is asked in the following comment:
Why doesn't it go negative?
Because while in integer computation the second computation is equivalent to 25 * 2^32
where ^
has the power meaning and 2^32
integer value is 0
. However, to explain why it's value is 0
: In binary:
100 * 1024 * 1024 * 1024 == 25 * 2^32;
Integer.MAX_VALUE = 2 ^ 31 -1 = 0 11111111 11111111 11111111 1111111
Integer.MAX_VALUE + 1 = 2 ^ 31 = 1 00000000 00000000 00000000 0000000
2 ^ 31
is a negative integer(-2147483648
) as the sign bit is 1
And hence 2 ^ 32
is just a multiplication of 2
to 2 ^ 31
: a left shift and the sign bit will become 0
and hence the result is 0
.
Check out the java language specification: 4.2.2: Integer operation
for details.