Quick revision
The short answer
There are five numeric bugs. (lo + hi) / 2 overflows for large indexes, so we use lo + (hi - lo) / 2 or (lo + hi) >>> 1. hashCode() can be negative and % keeps the sign, so the bucket can be negative; Math.floorMod fixes it. Math.abs(Integer.MIN_VALUE) is still negative because 2^31 does not fit in an int, and Math.absExact throws instead. Three million values near 1,000 sum to about 3 billion, beyond Integer.MAX_VALUE, so the total needs a long or Math.addExact. And 0.1 + 0.2 is 0.30000000000000004 in binary floating point, so price == 0.3 is false; money belongs in BigDecimal or long cents.
What to remember
In this answer, we found five numeric bugs. The midpoint (lo + hi) / 2 overflows, fixed with lo + (hi - lo) / 2 or an unsigned shift. hashCode() % buckets can be negative, fixed with Math.floorMod. Math.abs(Integer.MIN_VALUE) stays negative, so we use Math.absExact or avoid abs. An int sum of 3 million values near 1,000 wraps past Integer.MAX_VALUE, fixed with a long accumulator or Math.addExact. And 0.1 + 0.2 is not 0.3 in binary floating point, so money uses BigDecimal with compareTo or long cents. Static analysis tools catch several of these patterns automatically.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
There are five numeric bugs. (lo + hi) / 2 overflows for large indexes, so we use lo + (hi - lo) / 2 or (lo + hi) >>> 1. hashCode() can be negative and % keeps the sign, so the bucket can be negative; Math.floorMod fixes it. Math.abs(Integer.MIN_VALUE) is still negative because 2^31 does not fit in an int, and Math.absExact throws instead. Three million values near 1,000 sum to about 3 billion, beyond Integer.MAX_VALUE, so the total needs a long or Math.addExact. And 0.1 + 0.2 is 0.30000000000000004 in binary floating point, so price == 0.3 is false; money belongs in BigDecimal or long cents.
Why this question is asked
Numeric bugs are some of the most expensive bugs in production, because the code does not crash. It silently computes a wrong index, a negative bucket, a wrapped total or a price that is off by a fraction of a cent, and the damage appears far from the cause. Interviewers give a snippet like this to see whether we know how Java's int and double actually behave at their limits. In this answer, we will recap how int overflow and floating point work, then go through the snippet line by line, showing each bug with real values, the fix and why it works, and finish with the static analysis rules that catch these automatically.
1A Quick Recap of How Java Numbers Fail
Java's int is a 32-bit two's complement number with a range from -2,147,483,648 to 2,147,483,647. When an operation produces a result outside that range, Java does not throw; it wraps around, keeping only the low 32 bits, so Integer.MAX_VALUE + 1 becomes Integer.MIN_VALUE. Long has the same behaviour at 64 bits. The Math.addExact, multiplyExact, subtractExact and absExact methods are the exceptions: they throw ArithmeticException on overflow.
double is a 64-bit binary floating point number. It represents values as a binary fraction times a power of two, so decimal fractions like 0.1, which are infinite repeating fractions in binary, are stored as the nearest representable value. Small representation errors appear in arithmetic, and exact comparison with == fails.
2Bug 1: The Midpoint Overflows
int mid = (lo + hi) / 2 is the classic binary search bug, famously present for years in the JDK's own Arrays.binarySearch. If lo and hi are both large, for example indexes into an array of more than a billion elements, their sum exceeds Integer.MAX_VALUE and wraps to a negative number, and mid becomes a negative index.
lo + (hi - lo) / 2 never overflows because hi - lo is at most the array length and adding half of it to lo stays below hi. (lo + hi) >>> 1 works for non-negative lo and hi because the wrapped sum still has the correct 32 bits as an unsigned number, and the unsigned shift divides it by two correctly. Both are standard; the second is what the JDK uses now.
3Bug 2: A Negative Hash Gives a Negative Bucket
int bucket = key.hashCode() % buckets looks like it gives a value from 0 to buckets - 1, but in Java the remainder takes the sign of the dividend. Half of all hash codes are negative, so half the keys get a negative bucket, and the next array access throws ArrayIndexOutOfBoundsException, or worse, a map keyed by bucket number quietly gets entries in buckets that do not exist.
Math.floorMod returns a result with the sign of the divisor, so it is always in 0 to buckets - 1 for a positive bucket count. The common alternative, Math.abs(hashCode) % buckets, is not safe, because of the next bug: the string "polygenelubricants" has a hash code of exactly Integer.MIN_VALUE, and its absolute value is still negative.
4Bug 3: Math.abs Can Return a Negative Number
The range of int is asymmetric: there is one more negative value than positive values. The absolute value of -2,147,483,648 would be 2,147,483,648, which does not fit, so Math.abs(Integer.MIN_VALUE) wraps back to Integer.MIN_VALUE. The Javadoc documents this, but few people read it. The same happens for negating it with a minus sign, and for Long.MIN_VALUE.
Math.absExact, added in Java 15, throws instead of returning a wrong value, which is the right choice when MIN_VALUE indicates a bug. For bucket calculations, floorMod avoids the issue entirely, and HashMap's own approach, masking with (n - 1) & hash for power-of-two sizes, never produces a negative index.
5Bug 4: The Total Overflows
int total = 0; for (int v : values) total += v; with 3 million values near 1,000 should produce about 3,000,000,000. Integer.MAX_VALUE is about 2.147 billion, so the total wraps somewhere around the 2.15 millionth element and ends negative. Nothing throws; the report just shows a negative revenue.
The fix is to accumulate in a long, which holds sums up to about 9.2 x 10^18. Note that IntStream.sum() returns an int and overflows the same way, so we convert with asLongStream() first. When the total must fit in an int for some reason, Math.addExact makes the failure loud instead of silent, which is far better than a wrong number in a report.
6Bug 5: Comparing Doubles With == for Money
double price = 0.1 + 0.2; if (price == 0.3) charge(); never charges. Neither 0.1 nor 0.2 is exactly representable in binary, their sum is the double nearest to 0.30000000000000004, and that is a different double from the one nearest to 0.3. The deeper bug is using double for money at all: small errors accumulate across additions and multiplications and show up as invoices that are off by a cent.
| Line | What goes wrong | Fix |
|---|---|---|
| (lo + hi) / 2 | sum overflows, mid negative | lo + (hi - lo) / 2 or (lo + hi) >>> 1 |
hashCode() % buckets | negative remainder | Math.floorMod(hash, buckets) |
Math.abs(Integer.MIN_VALUE) | still MIN_VALUE | Math.absExact or avoid abs |
| int total += v | 3 billion wraps negative | long accumulator or Math.addExact |
| 0.1 + 0.2 == 0.3 | false in binary floating point | BigDecimal.compareTo or long cents |
For money we use BigDecimal, created from strings or with BigDecimal.valueOf, compared with compareTo, or we store amounts as long cents. For scientific doubles where approximation is acceptable, we compare with a tolerance, Math.abs(a - b) < 1e-9, chosen for the scale of the values.
7Follow-up questions
Which static analysis rules catch some of these?
Several tools have rules for exactly these patterns; check the rule names for your tool version. SpotBugs reports IM_AVERAGE_COMPUTATION_COULD_OVERFLOW for (lo + hi) / 2, RV_ABSOLUTE_VALUE_OF_HASHCODE for Math.abs(hashCode()), and FE_FLOATING_POINT_EQUALITY for == on doubles. SonarQube has rules against testing floating point numbers for equality and against Math.abs on values that could be MIN_VALUE. Error Prone flags new BigDecimal(double) and some integer overflow patterns. IntelliJ IDEA inspections also catch floating point equality and integer multiplication that is implicitly widened to long. None of them reliably catches a loop sum overflowing, so that one needs code review, tests with realistic sizes, or addExact.
Why does Java not throw on overflow by default?
Wrapping arithmetic matches what CPUs do natively, so it is fast, and Java inherited the behaviour from C. Checking every operation would slow down all arithmetic. The exact methods let us opt in where correctness matters more than speed.
Is float or double ever acceptable for money?
For rough analytics, such as an average order value on a dashboard, a double is fine. For anything that is billed, reconciled or audited, no: use BigDecimal with explicit rounding or integer minor units.
8Conclusion
In this answer, we found five numeric bugs. The midpoint (lo + hi) / 2 overflows, fixed with lo + (hi - lo) / 2 or an unsigned shift. hashCode() % buckets can be negative, fixed with Math.floorMod. Math.abs(Integer.MIN_VALUE) stays negative, so we use Math.absExact or avoid abs. An int sum of 3 million values near 1,000 wraps past Integer.MAX_VALUE, fixed with a long accumulator or Math.addExact. And 0.1 + 0.2 is not 0.3 in binary floating point, so money uses BigDecimal with compareTo or long cents. Static analysis tools catch several of these patterns automatically.
Open with
I see five bugs. The midpoint lo plus hi over two overflows when both indexes are large, for example 1.5 and 2 billion, and gives a negative mid, so I would write lo plus hi minus lo over two, or lo plus hi unsigned-shifted right by one.
Then, if they want more
The bucket calculation uses hashCode mod buckets, but hash codes are negative half the time and Java's remainder keeps the sign, so I would use Math.floorMod, which always returns a value between zero and buckets minus one.
Math.abs of Integer.MIN_VALUE is still negative, because two to the 31 does not fit in an int, so abs of a hash code is not a safe fix either; there is even a string, polygenelubricants, whose hash is exactly MIN_VALUE. If I need an absolute value, Math.absExact throws instead of lying.
The sum of three million values around a thousand is about three billion, which is above Integer.MAX_VALUE of about 2.1 billion, so the int total silently wraps to a negative number; I would accumulate in a long, or use Math.addExact to fail loudly.
And 0.1 plus 0.2 is 0.30000000000000004 in binary floating point, so the equality check is false and the customer is never charged. Money should not be a double at all: I would use BigDecimal created from strings and compared with compareTo, or long cents. Tools like SpotBugs, Sonar and Error Prone have rules for several of these patterns.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 15
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Review this code and list every numeric bug:": https://scrivio-interview-library.netlify.app/java/coding-problems/7dee507d18/