Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

long Divison

 
Abhishek Kanchan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers,

I am getting a very unexpected output for this one.Please help me know why it is so.

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

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

System.out.println(microsec/millisec); // Prints 5.7946..... ??
:roll:
 
Rob Spoor
Sheriff
Pie
Posts: 20526
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is in integer overflow.
24, 60, 60, 1000 and 1000 are all integer constants. As a result, the result of applying any mathematical operator to them will also be integer. However, 86400000000 does not fit into an integer; it will overflow several times to 500654080.

If you change the first 60 to 60L, the entire calculation will be using long as the result type, and you will have no problem.
 
Abhishek Kanchan
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob,
nice explaination
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic