Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java long assignment confusing

Why does this java code

long a4 = 1L;
long a3 = 1;
long a2 = 100L * 1024 * 1024 * 1024;
long a1 = 100 * 1024 * 1024 * 1024;
System.out.println(a4);
System.out.println(a3);
System.out.println(a2);
System.out.println(a1);

when run, output

1
1
107374182400
0

instead of the expected

1
1
107374182400
107374182400

output?

like image 456
tomsv Avatar asked Jan 21 '26 03:01

tomsv


1 Answers

 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.

like image 200
Sage Avatar answered Jan 23 '26 21:01

Sage



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!