int(primitive) value not getting typecasted to long(primitive) implicitly

147 views Asked by At

My question appears very simple.

int i =99999;
long square = i*i;
System.out.println(square);   //prints 1409865409 - incorrect value

int i = 99999;
long square = (long) i*i;
System.out.println(square);  // prints 9999800001 - correct value

It looks to be the range issue of int. But shouldn't it typecast the product to long implicitly? What am I missing here? I know how to use Math.pow(double,double) function and it works perfectly. But I want to know the reason for above output.

TIA.

2

There are 2 answers

0
Jean Logeart On

In the first case, the result is first computed as an int, and only then converted to a long.

Therefore the wrong result.


In the second case, i is converted to a long before computing the result because (long) (cast to long) has a higher precedence than *.

Therefore the right result.

0
Sam Estep On

You have fallen prey to an operator precedence error. This line:

long square = (long) i*i;

actually does this:

long square = ((long) i)*i;

This is important, because when you multiply 99999, you get a number too large to represent as an int. This line:

long square = i*i;

squares i, causing an overflow error, then casts the result to a long and assigns it to square. The other line casts the first factor to a long, forcing it to cast the second factor to a long as well, before the calculation takes place.