Sub topic 4
Numeric Types, Promotion, Division, and Overflow
Java needs to know what kind of number it is working with. That type affects the result of an operation. For example, 7 / 2 gives 3, but 7.0 / 2 gives 3.5.
This chapter assumes you know Java variables and basic data types, and can write and run a simple Java program.
Whole numbers and decimal numbers
Java has several numeric types. A type sets limits on the values a variable can hold.
A bit is a small unit of stored information. The number of bits helps determine a type’s range and precision.
| Type | Bits | What it stores |
|---|---|---|
| `byte` | 8 | Whole numbers from -128 to 127 |
| `short` | 16 | Whole numbers from -32,768 to 32,767 |
| `int` | 32 | Whole numbers from about -2.1 billion to 2.1 billion |
| `long` | 64 | A much wider range of whole numbers |
| `char` | 16 | A character code unit, also usable as a number from 0 to 65,535 |
| `float` | 32 | Floating-point numbers, with about 7 significant decimal digits |
| `double` | 64 | Floating-point numbers, with about 15 to 16 significant decimal digits |
A floating-point number is a number stored in a form that can represent fractions. A significant digit is a digit that contributes to a number’s precision. For example, 123.45 has five significant digits.
The whole-number types store values exactly within their ranges. Floating-point types can hold very large and very small values, but many decimal fractions are only approximations.
A literal is a value written directly in code. A whole-number literal such as 42 is normally an int. Add L to make it a long, as in 42L. A decimal literal such as 2.5 is a double by default. Add f to make it a float, as in 2.5f.
Numeric promotion
Numeric promotion is Java’s rule for choosing a type for a numeric operation. For ordinary arithmetic with two operands, Java chooses the first matching rule:
- If either operand is a
double, the operation usesdouble. - Otherwise, if either operand is a
float, it usesfloat. - Otherwise, if either operand is a
long, it useslong. - Otherwise, it uses
int.
An operand is a value an operator works on. For example, in 7.0 / 2, the operands are 7.0 and 2. The first is a double, so Java converts the 2 to a double for the division. The result is 3.5.
Values of type byte, short, and char are promoted to int for ordinary arithmetic. So adding two byte variables produces an int, even if the answer would fit in a byte.
Promotion happens before the operation. The type of the variable receiving the result does not change how the operation was done.
Division depends on the operands
When both operands are whole-number types, division drops the fractional part. It does not round to the nearest whole number.
7 / 2is3.-7 / 2is-3.
This rule is called truncation toward zero: Java removes the fraction, whether the answer is positive or negative.
To keep a fractional result, make at least one operand floating-point. For example, 7.0 / 2 is 3.5.
Assigning a whole-number result to a double happens too late to save the fraction. In double result = 7 / 2;, Java first calculates 7 / 2 as 3, then stores that result as 3.0.
Overflow
Overflow happens when a result is outside the range its type can hold. In int and long arithmetic, an overflowing result normally wraps around rather than causing an error.
For example, the largest int is 2,147,483,647. Adding 1 gives -2,147,483,648, the smallest int. This is not the answer you would expect from ordinary math.
A larger receiving variable does not prevent overflow if the operation already used int. For example, 2_000_000_000 * 2 uses int arithmetic. Its result overflows before it can be stored in a long.
Make an operand a long first: 2_000_000_000L * 2. Now the multiplication uses long arithmetic and gives 4,000,000,000.
Java provides methods such as Math.addExact when you want to detect overflow. If the result does not fit, the method throws an ArithmeticException. An exception is a signal that an operation could not complete normally.
Try the rules
Save this program as NumericDemo.java:
public class NumericDemo {
public static void main(String[] args) {
// Division
int whole = 7 / 2;
double fractional = 7.0 / 2;
double tooLate = 7 / 2;
System.out.println(whole); // 3
System.out.println(fractional); // 3.5
System.out.println(tooLate); // 3.0
System.out.println(-7 / 2); // -3
// Small whole-number types are promoted to int.
byte first = 100;
byte second = 30;
int sum = first + second;
System.out.println(sum); // 130
// Overflow can happen before assignment.
int wrapped = Integer.MAX_VALUE + 1;
long wrong = 2_000_000_000 * 2;
long right = 2_000_000_000L * 2;
System.out.println(wrapped); // -2147483648
System.out.println(wrong); // -294967296
System.out.println(right); // 4000000000
// Detect overflow instead of accepting a wrapped result.
try {
int checked = Math.addExact(Integer.MAX_VALUE, 1);
System.out.println(checked);
} catch (ArithmeticException error) {
System.out.println("Addition overflowed");
}
// Floating-point values can be approximate.
System.out.println(0.1 + 0.2); // 0.30000000000000004
}
}Compile and run it from the same folder:
javac NumericDemo.java
java NumericDemoThe comments show the output. Check especially the two multiplication results: changing one operand to long changes the type used for the multiplication.
Division by zero and special results
Whole-number division by zero throws an ArithmeticException. For example, an int divided by zero cannot produce an int result.
Floating-point division follows different rules:
1.0 / 0.0produces positive infinity.-1.0 / 0.0produces negative infinity.0.0 / 0.0producesNaN, which means “not a number.”
A very large floating-point result can also become infinity. Floating-point arithmetic does not wrap around like int arithmetic.
There is one unusual whole-number division overflow: Integer.MIN_VALUE / -1 produces Integer.MIN_VALUE. The positive answer is too large for an int, and this division does not throw an exception.
Floating-point precision
Many decimal fractions cannot be stored exactly as float or double. The program’s 0.1 + 0.2 example shows a small difference from the expected 0.3.
This matters when exact decimal answers are required. For money, consider Java’s BigDecimal type rather than relying on double. For measurements, a small approximation may be acceptable, but you should choose an appropriate limit for error.
Practice
Try each question before reading its answer.
Exercise
What are the values of 7 / 2 and 7 / 2.0?
Show answer
They are 3 and 3.5. The first uses whole-number division; the second uses double division.
Exercise
Why does double result = 7 / 2; store 3.0 rather than 3.5?
Show answer
Java divides two ints first, giving 3. It then converts that result to double for storage.
Exercise
Why does 2_000_000_000 * 2 overflow even if its result is assigned to a long? How can you prevent it?
Show answer
Both operands are ints, so multiplication uses int before assignment. Write one operand as a long, such as 2_000_000_000L * 2.
Exercise
What happens when an int is divided by zero? What does 1.0 / 0.0 produce?
Show answer
Integer division throws an ArithmeticException. The floating-point expression produces positive infinity.