Video lecture
Watch on YouTube(opens in a new tab)Sub topic 13
Overflow and Floating-Point Precision
Numbers in a Java program have limits. A whole-number calculation can produce a result that is too large for its type. A calculation with a decimal point can produce an answer that is close to, but not exactly, the expected value.
This chapter shows how to spot both problems and how to choose a safer approach.
Whole-number overflow
A type’s range is the set of values it can hold. An int can hold whole numbers from -2,147,483,648 through 2,147,483,647.
Overflow happens when a calculation produces a whole-number result outside the range of its type. For ordinary int arithmetic, Java does not stop the program. Instead, the result wraps around into the range.
For example, adding 1 to the largest int gives the smallest int. Subtracting 1 from the smallest gives the largest. The answer is a valid int, but it is not the answer you wanted.
Try overflow
Save this program as OverflowExample.java:
class OverflowExample {
public static void main(String[] args) {
int largest = 2_147_483_647;
int smallest = -2_147_483_648;
System.out.println(largest + 1);
System.out.println(smallest - 1);
int product = 50_000 * 50_000;
System.out.println(product);
long largerProduct = 50_000L * 50_000;
System.out.println(largerProduct);
}
}The underscores make long numbers easier to read. They do not change the values.
Compile and run the program:
javac OverflowExample.java
java OverflowExampleThe output is:
-2147483648
2147483647
-1794967296
2500000000The correct product of 50,000 and 50,000 is 2,500,000,000. That is too large for an int, so the first multiplication overflows.
The last multiplication uses 50_000L. The L makes that value a long, a whole-number type with a wider range. The multiplication is then done using long values, and the correct result fits.
A long can overflow too. It has a wider range, not an unlimited one. Even division has an edge case: dividing the smallest int by -1 overflows because the positive answer is too large for an int.
Detecting overflow
Sometimes wrapping is not acceptable. For example, a program should not silently turn a large account balance into a negative number.
Java provides methods that check whole-number arithmetic. Math.addExact adds two numbers and checks whether the result fits. If it does not, the method throws an exception, a signal that an operation could not finish normally.
This program catches the exception so it can report the problem:
class CheckedAddition {
public static void main(String[] args) {
int largest = 2_147_483_647;
try {
int result = Math.addExact(largest, 1);
System.out.println(result);
} catch (ArithmeticException problem) {
System.out.println("The result does not fit in an int.");
}
}
}The output is:
The result does not fit in an int.Java also provides Math.subtractExact and Math.multiplyExact. These checks help you detect a problem; you still need to decide what your program should do, such as reject the input or use a wider type.
Floating-point rounding
Floating-point numbers are numbers stored in a form that can represent fractions as well as very large or very small values. Java’s float and double are floating-point types.
Computers store these values using binary, a number system based on 0 and 1. Some decimal fractions cannot be stored exactly in binary, just as one-third cannot be written exactly with a limited number of decimal digits. Java stores a nearby value instead.
This limit is called precision: the amount of detail a number can hold. A double has more precision than a float, but neither can hold every decimal fraction exactly. A double typically provides about 15 to 16 significant decimal digits. Significant digits are the digits that carry detail in a number, apart from leading zeros.
Try a decimal calculation
Save and run this program as PrecisionExample.java:
class PrecisionExample {
public static void main(String[] args) {
double sum = 0.1 + 0.2;
System.out.println(sum);
System.out.println(sum == 0.3);
double large = 10_000_000_000_000_000.0;
System.out.println(large + 1.0 == large);
}
}The output is:
0.30000000000000004
false
trueThe first result is close to 0.3, but it is not exactly the same stored value. Therefore, sum == 0.3 is false.
The last result shows another precision limit. At that large value, the difference made by adding 1.0 is too small to be stored in the result. The result rounds back to the value of large.
Not every fraction has this problem. For example, 0.5 can be stored exactly as a double. The difficulty is knowing whether all the values and calculations in your program can be stored exactly.
Comparing approximate results
When a result is meant to be approximate, you can compare how far apart two values are instead of requiring exact equality.
A tolerance is the largest difference you are willing to accept. For the sum above, this test uses a tolerance of 0.000000001:
class ToleranceExample {
public static void main(String[] args) {
double sum = 0.1 + 0.2;
double expected = 0.3;
double tolerance = 0.000000001;
boolean close = Math.abs(sum - expected) < tolerance;
System.out.println(close);
}
}Math.abs returns the distance from zero, so the test works whether sum is slightly above or below expected. It prints true.
There is no single tolerance that works for every task. A useful choice depends on the size of the numbers and how much error the task can accept. A test suited to distances between cities may not suit the width of a tiny part.
Special floating-point results
Floating-point arithmetic can produce special values rather than an ordinary number:
- Infinity represents a result beyond the available floating-point range. For example,
Double.MAX_VALUE * 2.0produces positive infinity. - NaN means “not a number.” An operation such as
0.0 / 0.0produces NaN. - Underflow can happen when a nonzero result is too close to zero to be stored. For example,
Double.MIN_VALUE / 2.0becomes0.0. Despite its name,Double.MIN_VALUEis the smallest positive nonzerodouble, not the most negative one.
Use Double.isInfinite(value) to test for infinity and Double.isNaN(value) to test for NaN. Do not use value == Double.NaN: even NaN is not equal to itself.
Dividing a nonzero floating-point value by 0.0 produces infinity. By contrast, whole-number division by zero throws an ArithmeticException.
When exact decimal answers matter
For money and other tasks that require exact decimal values, a double may be a poor fit. One option is BigDecimal, a Java type for decimal arithmetic. Create values from text so the starting decimal values are exact:
import java.math.BigDecimal;
class MoneyExample {
public static void main(String[] args) {
BigDecimal first = new BigDecimal("0.10");
BigDecimal second = new BigDecimal("0.20");
BigDecimal total = first.add(second);
System.out.println(total);
}
}This prints 0.30. Some decimal calculations, such as division that does not end, still need an explicit rounding rule.
Another option is to store money as whole units of the smallest currency amount, such as cents. That avoids decimal fractions, but the whole-number type can still overflow, so its range and calculations need checking.
A practical check
Before using a numeric result, ask:
- Can the result be larger or smaller than the whole-number type allows?
- Is the calculation performed in a type wide enough for the result?
- If the value is floating-point, is a small difference acceptable?
- Does the task require an exact decimal answer instead?
Exercises
Exercise
What does adding 1 to the largest int produce with ordinary Java arithmetic?
Show answer
It wraps to the smallest int, -2147483648. Use Math.addExact to detect this overflow instead.
Exercise
Why can 0.1 + 0.2 == 0.3 be false when the values are doubles?
Show answer
Some decimal fractions are stored as nearby binary values. The calculated sum is close to, but not exactly equal to, the stored value of 0.3.
Exercise
How can you multiply two int-sized values when the correct result may be too large for an int but fits in a long?
Show answer
Make at least one value a long before multiplying, such as 50000L * 50000. Storing an already-overflowed int result in a long is too late.