Tuesday, February 13, 2007

A bug that is easily overlooked

Today I found a bug at work. The program is simple but the bug is easily overlooked. Here is the program (Java):
long timeSpan = 90 * 24 * 3600 * 1000;
System.out.println(timeSpan);
What is the result of execution?

This line is to calculate the total milliseconds of 90 days. The correct result shoudl be 7776000000, but the above program prints -813934592. We all know that it is numerical overflow. But why it is overflowed even I am already using long?

The problem is Java uses integer to store the intermediate result before assigning to the final variable. The correct syntax should be:
long timeSpan = 90L * 24 * 3600 * 1000;
System.out.println(timeSpan);

No comments: