This is because 121932631112635269 is greater than max int, so when doing n1 * n2, the result parsed to int will be garbage. The cast to Long is made after the math, when it tries to do the = with ans.
If you cast n1 and n2 to long before, doing the math you will get 121932631112635269.
int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = (long)n1 * (long)n2;
or like this:
int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = 1L * n1 * n2;
or if you change n1 and n2 types to long
edit: as Turing85 says,
the 2nd cast is superfluous
since the n1 would be cast to long before, there's no need to cast n2, since the result would be a Long. Making:
int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = (long)n1 * n2;
also correct
n1*n2is still anint-expression. I recommend to either definen1andn2aslongor cast one of the operatnds explicitly tolong.n1*n2is anint-expression, and the convertion frominttolongis widening, so there is not loss int he conversion.