简体   繁体   中英

Why my integer literal is not being promoted to long type when there is another long value in the expression?

Code:

public class Foo
{
    public static void main(String[] args)
    {
        long i = 4294967296l;
        System.out.println(i + 65536 * 65536);
        System.out.println(i + 65536L * 65536);
    }
}

Output:

4294967296
8589934592

It looks like in the first System.out.println statement, 65536 * 65536 is evaluated as int type as a result of which it wraps to 0 .

I want to know why in this statement, the numbers are not promoted to long . I thought that the presence of the long variable i in this statement would have been sufficient to promote 65536 to long as well.

在加法之前计算乘法(运算符优先级),因此首先将65536 * 65536计算为int乘法(因为两个操作数都是int文字),并且将结果提升为long以添加longint

The type of a multiplicative expression is the promoted type of its operands. If the promoted type is int or long, then integer arithmetic is performed. and The type of the unary plus expression is the promoted type of the operand.

any further clarification please use the link

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.15.3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM