Advertisement
Advanced Java, Java Fundamentals: Syntax, Data Types & Operators

How does Java's integer division and modulo operator behave with negative operands, and how does this differ from the mathematical definition of modulo used in some other contexts (like array indexing wraparound)?

Short answer

Java's integer division truncates toward zero (rather than always rounding down/toward negative infinity, which is how some other languages and pure mathematics define integer division), and the % (remainder/modulo) operator's result takes the SAME SIGN as the dividend (the left…

Save Java mock interview
Advertisement
AModel answer
Java's integer division truncates toward zero (rather than always rounding down/toward negative infinity, which is how some other languages and pure mathematics define integer division), and the % (remainder/modulo) operator's result takes the SAME SIGN as the dividend (the left operand), not necessarily the same sign as the divisor -- this means Java's % operator is more accurately described as a 'remainder' operator rather than a true mathematical modulo operator, and naively using % for something like wraparound array indexing with a potentially negative index will NOT produce the always-non-negative result a true mathematical modulo would, requiring an explicit adjustment (adding the divisor and taking % again) to achieve genuine non-negative wraparound behavior.
System.out.println(-7 / 2);   // -3, truncated toward zero (not -4, which flooring would give)
System.out.println(-7 % 2);   // -1, takes the sign of the DIVIDEND (-7), not always positive

// Naive wraparound indexing FAILS for negative indices
int index = -1;
int size = 5;
// int wrapped = index % size;  // -1, NOT the intended 4!

// Correct wraparound requires an explicit adjustment
int correctlyWrapped = ((index % size) + size) % size;  // 4, genuinely non-negative
Real-world example
A circular buffer implementation using naive % for wraparound indexing produces an ArrayIndexOutOfBoundsException when a computed index happens to go negative, traced to Java's % operator not behaving like true mathematical modulo for negative operands, fixed by adding the explicit ((x % n) + n) % n adjustment pattern.
Likely follow-ups
  • Why did Java choose truncating division/remainder-style modulo rather than flooring division/true modulo, given the latter avoids this specific pitfall?
  • How does Math.floorMod() differ from the % operator, and when should you prefer it?
Related topics