BackendBench
Coffee
Spot the Bug #13

Thirty days of milliseconds

A medium Java puzzle in the numeric overflow and precision family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.

mediumNumeric overflow and precisionbuggy line: 3

Highlighted: line 3. Play this one as a puzzle without the answer.

What is wrong

The multiplication runs in int arithmetic because every operand is an int, and 30 days in milliseconds is 2,592,000,000, which exceeds Integer.MAX_VALUE. The wrapped negative result is then widened to long. The assignment target does not change how the right side is calculated.

The fix

long millis = days * 24L * 60 * 60 * 1000;

How to avoid it next time

Make at least one operand long before the first multiplication, or use TimeUnit.DAYS.toMillis(days).

Want the background? Read Integer overflow and exact arithmetic in the Java concepts library.

About numeric overflow and precision

Java integers wrap around silently when they exceed their range, with no exception. int and long arithmetic, integer division and implicit narrowing casts all produce wrong numbers that look plausible.

In code review: Look at the type of every operand, not the type of the variable receiving the result. Multiplication of two ints happens in int even when assigned to a long. Use Math.addExact, long literals and BigDecimal for money.

More puzzles in this family

๐Ÿž Play today's puzzleAll 132 bugsโ† #12#14 โ†’

Frequently asked questions

What is the bug in "Thirty days of milliseconds"?

The multiplication runs in int arithmetic because every operand is an int, and 30 days in milliseconds is 2,592,000,000, which exceeds Integer.MAX_VALUE. The wrapped negative result is then widened to long. The assignment target does not change how the right side is calculated. The faulty line is line 3: long millis = days * 24 * 60 * 60 * 1000;

How do I fix it?

Replace it with: long millis = days * 24L * 60 * 60 * 1000;. Make at least one operand long before the first multiplication, or use TimeUnit.DAYS.toMillis(days).

How do I catch numeric overflow and precision in code review?

Look at the type of every operand, not the type of the variable receiving the result. Multiplication of two ints happens in int even when assigned to a long. Use Math.addExact, long literals and BigDecimal for money.

Is there a new puzzle every day?

Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.

More tools you might need