Java long assignment confusing

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

    107374182400 is exactly 25 times the full range of an integer (2^32), which means that if you try to fit it into an integer it will overflow. And because it would fit exactly 25 times it ends up precisely on 0 (this is a coincidence and other huge multiplications may end up either positive or negative). And you are using an integer right up to the point you cast to long

    long a1 = 100 * 1024 * 1024 * 1024;
    

    is equivalent to

    int temp = 100 * 1024 * 1024 * 1024;
    long a1 = (long)temp;
    

    If you put a single long in the expression, it is forced to use long maths not integer maths which removes the problem

提交回复
热议问题