Java long assignment confusing

前端 未结 9 1204
一个人的身影
一个人的身影 2021-01-24 05:17

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.pr         


        
9条回答
  •  长发绾君心
    2021-01-24 06:10

     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.

提交回复
热议问题