Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

A counter short hits is updated with hits += delta; where delta is an int from a request. Monitoring shows negative hit counts. Explain why the compiler did not stop this, and how you would review for it.

The compiler did not stop it because a compound assignment such as hits += delta includes a hidden cast: it means hits = (short) (hits + delta). The int sum is silently narrowed to a short, so any value above 32767 wraps around to a negative number. The plain form hits = hits + delta would not compile without an explicit cast, which would have forced someone to think about it. The fix is to use an int or long for counters, or Math.addExact with explicit range checks, and in review we look for compound assignments to narrow types, which static analysis can flag automatically.

Why this question is asked

This is a bug that passes code review, passes tests with small numbers, and only appears in production when traffic grows. Negative hit counts on a dashboard are the visible symptom; the cause is a rule of the language that most developers have never read. Interviewers ask it because it tests whether we know that compound assignment is not just shorthand, and whether we can turn one bug into a review practice. In this answer, we will recap the integer types and their ranges, reproduce the wrap-around, see exactly why the compiler allowed it, fix it, and then look at how to catch this whole class of bug in review.

1A Quick Recap of short and Integer Overflow

A short is a 16-bit signed integer, so it holds values from -32768 to 32767. An int is 32 bits and holds about plus or minus 2.1 billion. Java's integer arithmetic does not check for overflow: when a result is too large for its type, the extra high bits are simply dropped, and because of the two's complement encoding, a value just past the maximum becomes a large negative number. This is called wrapping around.

Java also never does arithmetic directly on short or byte. Before adding, both operands are promoted to int, so hits + delta is an int. The question is what happens when that int has to go back into a short variable.

2Reproducing the Negative Count

Let us take a counter that is already close to its limit and add a delta from a request.

Java
short hits = 32_000;
int delta = 1_000;
hits += delta;
System.out.println(hits); // -32536
// the same thing written out
short h2 = 32_000;
h2 = (short) (h2 + delta); // 33000 does not fit, keeps the low 16 bits
System.out.println(h2); // -32536

The true sum is 33000. A short can hold at most 32767, so the cast keeps only the low 16 bits, which represent 33000 - 65536 = -32536. Nothing throws, nothing logs, and the dashboard shows a negative count.

3Why the Compiler Accepted It

The Java Language Specification defines a compound assignment E1 op= E2 as E1 = (T) ((E1) op (E2)), where T is the type of E1. The cast to T is part of the definition. It exists so that common code like b += 1 for a byte compiles without noise, but it also means that any compound assignment can narrow a value silently.

Compare that with the plain assignment. hits = hits + delta assigns an int to a short, which is a narrowing conversion, and the compiler refuses it with an error saying there is a possible lossy conversion from int to short. Someone would have had to write the cast by hand, and a cast in a review is a visible question: can this value really fit? The compound form hid exactly that question.

Java
short hits = 0;
int delta = 5;
hits = hits + delta; // compile error: incompatible types: possible lossy conversion from int to short
hits += delta; // compiles: the narrowing cast is implicit
int total = 0;
total += 2.7; // compiles too: double narrowed to int, total is 2
long big = 5_000_000_000L;
int count = 0;
count += big; // compiles: long narrowed to int, count is 705032704
Step throughWhat hits += delta does
  1. Promote hits to int32000
  2. Add delta as int33000
  3. Implicit cast to shortkeeps the low 16 bits
  4. Store in hits-32536, no error

4 steps in order. Play them, or step through them one at a time.

The cast in step 3 is written by the language, not by us, so no one reviews it.

Notice the last two examples. The rule is not specific to short; any compound assignment where the right side is wider than the left narrows silently, including a double into an int and a long into an int.

4Fixing the Counter

The simplest fix is to stop using short for a counter. Saving two bytes per counter almost never matters, and an int holds two billion, a long nine quintillion. If the counter can be large or long-lived, long is the safe default. If we also want overflow to fail loudly instead of wrapping, Math.addExact throws ArithmeticException when an int or long sum overflows.

Java
long hits = 32_000;
hits += delta; // 33000
int safe = Math.addExact(Integer.MAX_VALUE, 1); // throws ArithmeticException: integer overflow
// if the value must stay a short, for example a smallint column, check the range explicitly
int next = storedHits + delta;
if (next > Short.MAX_VALUE) throw new IllegalStateException("hit count exceeds smallint");

Two more things are worth checking while we are here. A delta that comes from a request must be validated, since a negative or huge delta is either a bug or an attack. And a counter updated by many request threads should not be a plain field at all, because hits += delta is a read, an add and a write, and concurrent updates lose increments. An AtomicLong or a LongAdder fixes that, and a database column should be at least an integer type with the same range we expect.

5Reviewing for This Class of Bug

In review, we look for compound assignments where the left side is narrower than the right: byte, short or char variables updated with +=, -= or *=, int variables updated with long or double values, and counters declared with small types. Each one is a hidden cast, and the reviewer should ask the same question the explicit cast would have raised: can this value really fit?

Doing that by eye does not scale, so we let tools do it. Error Prone has a check for narrowing compound assignments (named NarrowingCompoundAssignment in the versions we know; check your version), and IntelliJ IDEA has inspections for implicit numeric conversions in compound assignments. Turning one of them on in the shared build turns a rule that people must remember into one that the build enforces.

6Follow-up questions

Why does Java allow the implicit cast at all?

For convenience with small types. Without it, even b += 1 for a byte b would need b = (byte) (b + 1), because b + 1 is an int. The designers chose readable code for the common case, at the cost of hiding narrowing in the rare dangerous one.

Would Math.addExact have caught the short overflow?

Not directly, because it only works on int and long. Math.addExact(32000, 1000) returns 33000 without complaint, since that fits in an int. For a short we must check against Short.MAX_VALUE ourselves, or better, not use short for a counter.

Is ++ on a short also a hidden narrowing?

Yes. hits++ on a short at 32767 gives -32768, for the same reason: the increment is done in int and narrowed back. The same review question applies.

7Conclusion

In this answer, we saw that a compound assignment like hits += delta is defined as hits = (short) (hits + delta), so the int sum is narrowed silently and values above 32767 wrap to negative. The plain assignment would not have compiled without a visible cast. We fixed the counter by using int or long, Math.addExact or explicit range checks, noted the validation and thread-safety issues next to it, and made the review practical by turning on static analysis for narrowing compound assignments.

What to say in the interviewAbout 90 seconds aloud

Open with

The compiler accepted it because a compound assignment has a cast built into its definition. hits += delta means hits = (short) (hits + delta). The addition is done in int, because short operands are promoted, and the result is then narrowed back to short without any warning.

Then, if they want more

A short tops out at 32767, so when the sum is, say, 33000, only the low 16 bits are kept and it becomes -32536, which is the negative count on the dashboard. If someone had written hits = hits + delta, it would not have compiled, because assigning an int to a short is a lossy conversion.

They would have needed an explicit cast, and that cast would have prompted the question in review. To fix it I would make the counter an int or, for anything long-lived, a long.

If overflow must fail loudly, I would use Math.addExact, which throws on int or long overflow, or an explicit range check if the value has to fit a smallint column. I would also validate the delta from the request and, since many threads update it, use an AtomicLong or LongAdder.

For review, I would look for compound assignments to narrow types and turn on a static analysis check for them, so the build catches it instead of people.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. 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 "A counter short hits is updated with hits += delta; where delta is an int from a...": https://scrivio-interview-library.netlify.app/java/operators-and-control-flow/203e681ef1/