Division by zero in Java
Integer /0 throws ArithmeticException; floating /0 gives Infinity or NaN.
Integers: crash
Integer / or % by zero throws ArithmeticException: / by zero. Integers have no way to represent infinity, so the JVM stops.
int total = 10, count = 0;
int avg = total / count;
// ArithmeticException: / by zeroYour turn
What happens?
int items = 12;
int boxes = 0;
System.out.println(items % boxes);012Throws ArithmeticException
Show the answer
Remainder by zero fails just like division: ArithmeticException.
Doubles: IEEE 754 rules
Floating-point math follows the IEEE 754 standard, which defines special values for these cases. No exception is thrown.
1.0 / 0 // Infinity
-1.0 / 0 // -Infinity
0.0 / 0.0 // NaN (not a number)
5.0 % 0 // NaNYour turn
What does this print?
System.out.println(3.0 / 0);
System.out.println(0.0 / 0);Infinity NaNThrows ArithmeticExceptionNaN NaN
Show the answer
3.0 is a double, so the 0 is promoted and IEEE rules apply: a positive number / 0 is Infinity, and 0.0 / 0 has no meaningful value: NaN.
One decimal point changes everything
If either operand is a double, the whole operation is floating-point. So 10 / 0 crashes, but 10 / 0.0 and 10.0 / 0 quietly give Infinity.
10 / 0 // ArithmeticException
10 / 0.0 // Infinity
10.0 % 0 // NaNWhich is worse?
A crash, or a silent Infinity: which is more dangerous in a real app?
Think about it, then reveal the answer
Often the silent one. An exception stops right at the bug. Infinity or NaN flows on through later calculations and surfaces far away, in a report or a database.
In real projects
Average of an empty list: sum / count with count 0. With ints, a crash in production; with doubles, a dashboard showing NaN. Real code checks if (count == 0) first.
Key takeaways
- int / 0 and int % 0 → ArithmeticException
- 1.0 / 0 → Infinity; -1.0 / 0 → -Infinity
- 0.0 / 0.0 and x % 0.0 → NaN
- One double operand makes the whole division floating-point
In 1997 the US Navy cruiser USS Yorktown was reportedly left dead in the water for hours after a zero entered into a database field caused a divide-by-zero in its control software.
Practice questions
What does this print?
System.out.println(1.0 / 0);- Throws ArithmeticException
- Infinity
- 0.0
- NaN
Check your answer
Infinity. 1.0 is a double, so 0 is promoted to 0.0 and floating-point rules apply: a positive number divided by zero is Infinity.
What does this print?
int total = 10;
int count = 0;
System.out.println(total / count);- Infinity
- 0
- NaN
- Throws ArithmeticException
Check your answer
Throws ArithmeticException. Both operands are ints, so this is integer division by zero, which always throws ArithmeticException.