Search code examples
javaandroidjvmdalvik

Casting result of multiplication two positive integers to long is negative value


I have code like this :

int a = 629339;
int b = 4096;
long res = a*b;

The result is -1717194752 but if I add one manual cast to long long res = ((long)a)*b; or long res = (long) a*b; the result is correct 2577772544 Who can explain how does it works.


Solution

  • long res = a*b;
    

    a*b will be treated as integer unless you add 'l' at end (or) cast.

    As per java tutorial

    The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else.