Lone Learner
Lone Learner

Reputation: 20688

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.

Upvotes: 3

Views: 90

Answers (2)

Zia
Zia

Reputation: 1011

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

Upvotes: 0

Eran
Eran

Reputation: 393956

Multiplication is evaluated before addition (operators precedence), so first 65536 * 65536 is evaluated as int multiplication (since both operands are int literals) and the result is promoted to long for the addition of a long and an int.

Upvotes: 10

Related Questions