Is it possible to lose precision in this case?

int X =  (some integer number);
Date D = new Date(X * 1000);
int Y  = (int)(D.getTime())/1000;

I would believe that Y would always be the same as X as long as X is some integer value. Is that correct?

有帮助吗?

解决方案

No!you're not correct! replace the line Date D = new Date(X * 1000);

with Date D = new Date(X * 1000L);

其他提示

Use long (64 bit) numbers not integers (32 bit) numbers. If you use integers it may overflow (go from positive to negative). See this link for details https://www.securecoding.cert.org/confluence/display/java/NUM00-J.+Detect+or+prevent+integer+overflow

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top