Java long assignment confusing

前端 未结 9 1088
一个人的身影
一个人的身影 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:08

    Here's what you did : You assigned 100 * 1024 * 1024 * 1024 to a long data type but you didn' said that 100 * 1024 * 1024 * 1024 is a long value

    By default java compiler thinks that its an integer. Since integer cannot hold that much value, it will show wrong result. Hope it helps !

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-24 06:15

    long a4 = 1L; //No problem in this

    long a3 = 1; //here left side primitive is considered as integer and at the time of assignment it will be casted to long so again result is as expected

    long a2 = 100L * 1024 * 1024 * 1024; (here you have used 100L so others will be type casted to Long so expected output)

    long a1 = 100 * 1024 * 1024 * 1024; (as by default any primitive digit is considered as int in java, it will consider this as integer multiplication so it goes out of range and results in 0)

    0 讨论(0)
提交回复
热议问题