Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

Have I gone crazy?

Ed Dablin
Ranch Hand
Posts: 32
I'm running this:

and Eclipse console gives answer as 1471228928
But my calculator says the answer is 31536000000
I thought I might have exceeded the max long value. But Oracle says:
The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).

Obviously I am doing something very, very stupid. But what?

Bear Bibeault
Author and ninkuma
Marshal
Posts: 64631
86
Your variable is a long, but the expression is not because the values in the expression are not. You can force the expression to be evaluated as long by making any one of the values a long literal (rather than the current int literals).

Ulf Dittmer
Rancher
Posts: 42967
73
No, you're not doing anything wrong. It's just that you're not aware of how Java determines the type of literal numbers..

The key insight is that "365*24*60*60*1000" is not a long expression, but an int expression, since all its constituent parts are ints - which overflows. You can force it to be a long expression by making one of its factors a long, e.g. the first one: "365l*24*60*60*1000". The "l" after 365 basically says to the compiler: never mind what this number looks like (and it looks like an int), treat it as a long.

Lean back and observe the difference :-)

Jeff Verdegan
Bartender
Posts: 6109
6
• 2
Ulf Dittmer wrote:by making one of its factors a long, e.g. the first one: "365l*24*60*60*1000". The "l" after 365 basically says to the compiler: never mind what this number looks like (and it looks like an int), treat it as a long.

Although I'd recommend a capital 'L', which doesn't look so much like the number 1 as lowercase 'l' does.

Ed Dablin
Ranch Hand
Posts: 32
Thanks all! Marked as resolved