Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding int operations out of range

 
Vasudhaiv Naresh
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
Thanks,
Naresh
 
Matt Russell
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Vasudhaiv Naresh:
Hi all,
Can anybody let me know how this "5" has come?
Thanks,
Naresh

Try the following instead:
 
Adeeb Abdul Karim
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Because
MAX VALUE of Long = 9223372036854775807
MIN VALUE of Long = -9223372036854775808
Value of A as Long = 86400000000

A/B = 100 , not 1000!
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic