Search code examples
javacastingintlong-integerprimitive

Integer parameters formula returns integer


Code below makes foo value as -1149239296 i. e. integer value which is out of bounds:

int bar = 3000;
long foo = bar * 1024 * 1024;

Seems like Java takes type of first parameter and tryes to return formula's result with that type. Where in Java specification one can read that story?

I made such suggestion cause

int bar = 3000;
long foo = (long)bar * 1024 * 1024;

actually returns sets long value to foo.


Solution

  • For this case, casting any of the int literals to long will work. But with longer chains of operators, where an overflow may occur somewhere in the middle, the associativity matters. The * operator is left-associative, according to the JLS Section 15.17, so the first literal should be a long to avoid overflowing ints from the start. Other math-related operators are also left-associative.

    The reason that only one of the literals being long is necessary is because of binary numeric promotion, Section 5.6.2 of the JLS, which will promote the narrower type to the wider type, at least int.