Integer division & remainder in Java
int / int truncates toward zero; % keeps the sign of the dividend.
isOdd(-3) returns false. Two bugs, one cause: integer division.int / int = int
When both operands are integers, / throws away the fractional part, truncating toward zero. Make one operand a double to keep the decimals.
7 / 2 // 3
-7 / 2 // -3 (toward zero, not -4)
7 / 2.0 // 3.5Your turn
What does this print?
System.out.println(9 / 4);
System.out.println(-9 / 4);2 -22.25 -2.252 -3
Show the answer
Both are int divisions, truncated toward zero: 2.25 → 2 and -2.25 → -2.
The remainder's sign
a % b always takes the sign of the left operand (the dividend). The divisor's sign doesn't matter. The rule a == (a / b) * b + a % b always holds.
-7 % 2 // -1 (-7 = -3*2 + -1)
7 % -3 // 1 (7 = -2*-3 + 1)Your turn
What does this print?
System.out.println(-10 % 3);
System.out.println(10 % -3);-1 12 -21 1
Show the answer
The result follows the dividend: -10 gives -1, and 10 gives 1, whatever the divisor's sign.
The isOdd bug
For negative odd numbers, n % 2 is -1, not 1, so this returns false for -3. Test n % 2 != 0 instead.
boolean isOdd(int n) {
return n % 2 == 1; // fails for -3
}Averages
int a = 3, b = 4;
double avg = (a + b) / 2;(a + b) / 2 is int division: 7 / 2 = 3, widened to 3.0 too late.
int a = 3, b = 4;
double avg = (a + b) / 2.0;2.0 is a double, so the division itself is floating-point.
Why not cast it?
Why doesn't double avg = (double) ((a + b) / 2); fix it?
Think about it, then reveal the answer
The int division has already thrown away the .5 before the cast runs: you're casting 3 into 3.0. An operand must be a double before dividing.
In real projects
Progress bars stuck at 0% are a classic: done / total * 100 with ints is 0 until the job finishes. Multiply first (done * 100 / total) or use doubles.
Key takeaways
- 7 / 2 is 3, and -7 / 2 is -3 (toward zero)
- -7 % 2 is -1: sign follows the dividend
- Make one operand a double to get decimals: 7 / 2.0
- Test odd numbers with n % 2 != 0
Languages disagree: Python's -7 // 2 is -4 (it rounds down), while Java's -7 / 2 is -3 (it truncates toward zero). Same numbers, different answers.
Practice questions
What does this print?
System.out.println(-7 / 2);
System.out.println(-7 % 2);- -4 1
- -3 1
- -4 -1
- -3 -1
Check your answer
-3 -1. Integer division truncates toward zero, so -3.5 becomes -3. The remainder takes the dividend's sign: -7 = -3 × 2 + (-1).
What does this print?
System.out.println(7 % -3);- -1
- -2
- 2
- 1
Check your answer
1. The sign of the divisor doesn't matter; the result follows the dividend 7, which is positive. 7 = -2 × -3 + 1.