This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes Please explain the behavior Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Please explain the behavior" Watch "Please explain the behavior" New topic

Please explain the behavior

Ramaswamy Srinivasan
Ranch Hand

Joined: Aug 31, 2004
Posts: 295
Hi All,

I came across this question, in an interview.

Can anyone please explain the reason, why this behaviour is exhibited.

Thanks a lot, in advance.

Manuel Moons
Ranch Hand

Joined: Mar 05, 2002
Posts: 229
The second result exceeds the value of an int. And because none of the values that are used in the constant expresssion (24*60*60...) are explicitly cast to a long, the result will also be an int. So the resulting value will not be able to fit in an int. Putting it in a long will not help because the value is already lost.

You can solve this by using the following code (notice the 24L):

[ August 01, 2005: Message edited by: Manuel Moons ]
Ryan McGuire
Ranch Hand

Joined: Feb 18, 2005
Posts: 1042
You mean why the output is "5"?

Because the expression for b is too big for an integer. You might think that it would be ok, since b is a long. Too bad the 24*60*60*1000*1000 calculation is done with plain old integers before the integer value is assigned to a long.

Fixing this would be as easy as making the 24 in the expression for b a long constant:

Once the 24 is a long, all the other constants are extended to longs and multiplied into the expression.
Ryan McGuire
Ranch Hand

Joined: Feb 18, 2005
Posts: 1042
I have got to learn to type faster. It is good to know that Manuel and I came up with the same solution.
jQuery in Action, 3rd edition
subject: Please explain the behavior
It's not a secret anymore!