java - Overflow occurs with multiplication -


long m = 24 * 60 * 60 * 1000 * 1000; 

the above code creates overflow , doesn't print correct result.

long m2 = 24l * 60 * 60 * 1000 * 1000; long m3 = 24 * 60 * 60 * 1000 * 1000l; 

the above 2 lines print correct result.

my questions are-

  1. does matter compiler use, m2 or m3?
  2. how java starts multiplying? left right or right left? 24*60 gets computed first or 1000*1000?

i use m2 line instead of m3 line.

java evaluates multiplication operator * left right, 24 * 60 evaluated first.

it happens 24 * 60 * 60 * 1000 (one 1000) doesn't overflow, time multiply 1000l (the second 1000), product promoted long before multiplying, overflow doesn't take place.

but mentioned in comments, more factors can cause overflow in int data type before multiplying last long number, yielding incorrect answer. it's better use long literal first (left-most) number in m2 avoid overflow start. alternatively, can cast first literal long, e.g. (long) 24 * 60 * ....


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -