Division by Zero: Runtime Exceptions and Special Values
What you'll learn: How Java handles division by zero differently for integers versus floating-point numbers.
The Core Idea
When you divide by zero in mathematics, the operation is undefined—but your Java program needs to handle this situation somehow. Java's response depends on whether you're working with integer types (int, long, short, byte) or floating-point types (float, double).
Integer Division by Zero: ArithmeticException
When you attempt to divide an integer by zero, Java immediately throws an ArithmeticException and your program crashes (unless you handle the error, which you'll learn later):
int a = 10;
int b = 0;
int result = a / b; // Throws ArithmeticException: / by zero
This is a runtime error—your code compiles fine, but fails during execution. The same happens with the modulus operator: 10 % 0 also throws ArithmeticException.
Floating-Point Division by Zero: Special Values
Floating-point division by zero does not crash. Instead, Java produces one of the special values you learned earlier:
double x = 10.0;
double y = 0.0;
double result = x / y; // result is Infinity (positive)
double z = -10.0 / 0.0; // z is -Infinity
double weird = 0.0 / 0.0; // weird is NaN (Not a Number)
These special values allow your program to continue running, though the results may be meaningless.
Why the Difference?
Think of it like two different number systems with different rules. Integers are exact and finite—division by zero has no valid answer, so Java stops immediately. Floating-point arithmetic already deals with approximations and special values, so it simply produces Infinity or NaN to represent impossible operations.
Key Takeaway: Integer division by zero throws ArithmeticException at runtime; floating-point division by zero produces Infinity or NaN without crashing.