Java division returns incorrect result -


 public static void main(string[] args) {         final long a= 24 * 60 * 60 * 1000 * 1000;         final long b= 24 * 60 * 60 * 1000;          system.out.println(a/b);  } 

it should return 1000, returns 5 why?

24 * 60 * 60 * 1000 86400000. if multiply 1000, overflow int type (because maximum value int can hold 2147483647 lot less 86400000000) , 500654080 a.

then, when divide result 86400000, 5.

in order fix this, need explicitly specify result multiplication long - because numeric operators in java produce integers, unless explicitly instructed produce other numeric type.

just appending l on of operands sufficient:

final long = 24 * 60 * 60 * 1000 * 1000l; 

Comments