Sub topic 4
Numeric Types, Promotion, Division, and Overflow
Java uses different numeric types for different kinds of numbers. The types in a calculation affect both the result and how much information it can hold.
Numeric types
An integer is a whole number, such as 7 or -3. A floating-point number can include a fractional part, such as 3.5.
| Type | Holds | Example |
|---|---|---|
| `int` | Integers from -2,147,483,648 to 2,147,483,647 | `7` |
| `long` | Integers in a larger range than `int` | `7L` |
| `float` | Floating-point numbers with less precision than `double` | `7.0f` |
| `double` | Floating-point numbers with more precision than `float` | `7.0` |
A literal is a value written directly in code. The L in 7L makes it a long literal. A whole-number literal without L, such as 7, is usually an int. The f in 7.0f makes it a float; 7.0 is a double.
Promotion and division
An operand is a value used by an operator. Numeric promotion is Java’s automatic conversion of numeric operands to suitable types before a calculation.
For example, when an int and a double are used together, Java converts the int to a double. In most calculations, smaller integer types such as byte and short are promoted to int.
Division depends on the operand types:
- If both operands are integers, Java drops the fractional part. It rounds toward zero, so
-7 / 2is-3. - If either operand is floating-point, the result is floating-point. For example,
7.0 / 2is3.5.
Storing a result in a double does not change how the earlier calculation was done.
Overflow
Overflow happens when an integer calculation produces a value outside its type’s range. Java’s ordinary integer arithmetic wraps around without a warning.
Using a long variable for the result is not enough if the calculation itself uses only int operands. Make an operand a long before the calculation instead.
Try it
Save this program as Numbers.java, then compile and run it.
public class Numbers {
public static void main(String[] args) {
int whole = 7 / 2;
double tooLate = 7 / 2;
double fractional = 7.0 / 2;
long wrapped = 2_000_000_000 + 1_000_000_000;
long safe = 2_000_000_000L + 1_000_000_000;
System.out.println(whole); // 3
System.out.println(tooLate); // 3.0
System.out.println(fractional); // 3.5
System.out.println(wrapped); // -1294967296
System.out.println(safe); // 3000000000
}
}In tooLate, integer division happens first. The result 3 is then converted to 3.0. In safe, the L makes the addition use long values, so this sum fits.
Exercise
What do 9 / 2 and 9 / 2.0 produce? Why are they different?
Show answer
They produce 4 and 4.5. The first uses integer division. In the second, 2.0 is a double, so Java promotes 9 to a double before dividing.