File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Have I gone crazy? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Have I gone crazy?" Watch "Have I gone crazy?" New topic
Author

Have I gone crazy?

Ed Dablin
Ranch Hand

Joined: Oct 09, 2012
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

Joined: Jan 10, 2002
Posts: 60810
    
  65

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).


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41155
    
  45
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 :-)


Ping & DNS - my free Android networking tools app
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: Oct 09, 2012
Posts: 32
Thanks all! Marked as resolved
 
Consider Paul's rocket mass heater.
 
subject: Have I gone crazy?
 
Similar Threads
Getting from long to int
long in a byte array
Autoboxing & Generics Caveat
Websphere CMP Custom primitive wrapper
Doubt regarding Garbage Collection found in K&B OCP Java 6 Practice Exams Book