aspose file tools*
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 The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Please explain the behavior" Watch "Please explain the behavior" New topic
Author

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.

Cheers,
Ram.
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: 1007
    
    3
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: 1007
    
    3
I have got to learn to type faster. It is good to know that Manuel and I came up with the same solution.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: Please explain the behavior