Ramaswamy Srinivasan
Ranch Hand
Posts: 295
Hi All,

I came across this question, in an interview.

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

Cheers,
Ram.

Manuel Moons
Ranch Hand
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
Posts: 1068
4
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
Posts: 1068
4
I have got to learn to type faster. It is good to know that Manuel and I came up with the same solution.