File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Regarding int operations out of range Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Regarding int operations out of range" Watch "Regarding int operations out of range" New topic

Regarding int operations out of range

Vasudhaiv Naresh
Ranch Hand

Joined: May 13, 2005
Posts: 57
Hi all,
I have encountered a strange piece of code whic goes like:
final long A = 24*60*60*1000*1000;
final long B = 24*60*60*10000;
System.out.println("A/B = "+A/B);
This gives "5" as against the expected value of "1000".
Can anybody let me know how this "5" has come?
Matt Russell
Ranch Hand

Joined: Aug 15, 2006
Posts: 165
Originally posted by Vasudhaiv Naresh:
Hi all,
Can anybody let me know how this "5" has come?

Try the following instead:

Inquisition: open-source mock exam simulator for SCJP and SCWCD
Adeeb Abdul Karim

Joined: Dec 22, 2004
Posts: 8
MAX VALUE of Integer = 2147483647
MIN VALUE of Integer = -2147483648
Value of A as Integer = 86400000000, it is more than what an integer can hold. So it rotates the bits, so current value is
24 * 60 * 60 * 1000 * 1000 = 500654080, instead of 86400000000
A = 500654080
B = 864000000
A/B = 0, not 5 !

Reason : When the numbers are participating in arithmatic operations, it will be converted to the type with highest capacity. Here all the participants are of int type. Hence multiplication and division happens on int; the LHS accepts it since long is a bigger type than iint, but does not have any role in operations.

As Matt Caripto suggested if you give 1000L and 10000L respectively, the arithmatic opertions will work in long type and A will be able to hold the full value of 86400000000.
MAX VALUE of Long = 9223372036854775807
MIN VALUE of Long = -9223372036854775808
Value of A as Long = 86400000000

A/B = 100 , not 1000!

�That which begins, also ends.�
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Funny, I have seen this code in a book recently. "Java Puzzlers" by Joshua Bloch, et al. The answer was given, and explained, there too.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
I agree. Here's the link:
subject: Regarding int operations out of range
It's not a secret anymore!