*
The moose likes Beginning Java and the fly likes long Divison Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "long Divison" Watch "long Divison" New topic
Author

long Divison

Abhishek Kanchan
Ranch Hand

Joined: May 10, 2007
Posts: 32
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:


SCJP 1.5<br />SCWCD 5.0
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Abhishek Kanchan
Ranch Hand

Joined: May 10, 2007
Posts: 32
Thanks Rob,
nice explaination
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: long Divison
 
Similar Threads
java.sql.Date - setting a future date?
Regarding int operations out of range
Question to Authors : What would the output be?
Please explain the behavior
Incrementing and Decrementing Variables