Java long assignment confusing

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

    As per the documentation of Lexical Literals it is mentioned that,

    The type of a literal is determined as follows:
    - The type of an integer literal (§3.10.1) that ends with L or l is long (§4.2.1).
    - The type of any other integer literal is int (§4.2.1).

    Thus your expression, 100 * 1024 * 1024 * 1024 is evaluated as int primitive data type because l or L is not mentioned in any numeric value. and the result is 107374182400 i.e. in Binary it is 1 1001 0000 0000 0000 0000 0000 0000 0000 0000 and int is 32-bit so low 32-bit are taken as mentioned in Example 4.2.2-1. Integer Operations which results to 0

    It is also mentioned in same documentation that,

    If an integer operator other than a shift operator has at least one operand of type long, then the operation is carried out using 64-bit precision, and the result of the numerical operator is of type long. If the other operand is not long, it is first widened (§5.1.5) to type long by numeric promotion

    It means any value in expression contains l or L then all the int values will be expanded to 64 bit.

    EDIT In the comment it is also asked

    Why doesn't it go negative?

    I think it also answers the above question

提交回复
热议问题