Denis
Denis

Reputation: 1229

long to int conversion in java not working

I am working on a problem with big number's in java.

int temp =0;
long last = 218212982912L;
temp = (int) last%10;
last = last/10;

for the above line of code I get the

temp = -4 

in the first iteration. I am not sure what is the problem. I have tried a lot of solution online available.

Upvotes: 4

Views: 652

Answers (2)

Pooya
Pooya

Reputation: 6126

The last positive you can get is 2,147,483,647 and when you are explicitly converting a larger number to int, your will get unpleasant results but if you put extra parentheses like (int) (someLong % 10), first the long operation get executed (which results in smaller long value that fits int memory space) and then you can cast it to int without worry

Upvotes: 1

nhouser9
nhouser9

Reputation: 6780

Put parentheses around last%10

The cast to int is being applied before the modulus operation

Upvotes: 5

Related Questions