Java long assignment confusing

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

    In Java, if you have int * int, it will compute the output as an int. It only gives the result as a long if you do int * long. In your case, the 100 * 1024 * 1024 * 1024 has a result that overflows int.

    So, adding a "L" makes the operand to be a long, and the computation stores the values in long. And of course, no overflow occurs and a correct result can be outputed (i.e. a2).

提交回复
热议问题