Division, casts, and overflow
1.2.2 — Division, casts, and overflow
Learn how Java chooses numeric results: integer and decimal division, remainder, parentheses, casts, and overflow.
int holds whole numbers, long holds larger whole numbers, and double holds approximate numbers that can have fractional parts. A declaration such as int value = 7; creates a variable with an initial value.
System.out.println(...) prints a value. The examples declare their own inputs; you do not need another lesson’s variables.
Division depends on the operands
An operand is a value an operator works with. In 7 / 2, 7 and 2 are the operands and / is the division operator.
Both operands here are int values. Integer division produces a whole-number quotient. It discards the fractional part, rounding toward zero.
Predict the next expression. It will not automatically switch to a fractional type just because the mathematical answer has a half.
Writing 2.0 makes that operand a double. For this division, the int operand is converted to double too, and the result is double. This is a simple case of numeric promotion.
The rule applies to the calculation, not just to the variable that receives its result. If integer division already discarded the fraction, putting its answer in a double does not recover the half.
Remainder
% gives the remainder after integer division. 7 / 2 is 3, and 7 % 2 is 1.
You can check the result using:
total = quotient * divisor + remainderHere, 3 * 2 + 1 reconstructs 7. Run the next cell to see all three values.
Negative integer division
Integer division discards the fractional part toward zero. -7 / 2 is -3, rather than -4.
The integer remainder has the sign of the left operand, or is zero. -7 % 2 is -1. The check still works: (-3) * 2 + (-1) is -7.
Precedence decides which operation happens first
Java does not always evaluate an expression from left to right without regard to its operators. Multiplication, division, and remainder have higher precedence than addition and subtraction.
Parentheses explicitly group an expression. Operators of the same precedence in these examples group from left to right.
| Expression | Steps | Result |
|---|---|---|
| 2 + 3 * 4 | 3 * 4, then add 2 | 14 |
| (2 + 3) * 4 | 2 + 3, then multiply by 4 | 20 |
| 20 / 3 * 3 | Integer division first gives 6; multiply by 3 | 18 |
Use parentheses when they make your intended grouping clearer to the next reader. Do not depend on the reader remembering every precedence rule.
Casts convert values
A cast puts a type in parentheses before a value or expression.
(double) (7 / 2) // integer division gives 3, then the cast gives 3.0
(double) 7 / 2 // convert 7 first, so division gives 3.5Cast an operand before division if you want double division. Casting the result cannot restore a discarded fraction.
A cast from an in-range double to int also discards the fractional part toward zero: (int) 3.9 is 3, and (int) -3.9 is -3. It does not round to the nearest integer.
Overflow: the answer does not fit
An int has a finite range: -2,147,483,648 to 2,147,483,647. Multiplying 50,000 by 50,000 mathematically gives 2,500,000,000, which is outside that range.
Ordinary int arithmetic does not automatically switch to long or throw an error on overflow. It wraps to an int value. The resulting number may be negative even though both inputs were positive.
This is another case where a wider destination alone is too late. The multiplication is evaluated before its result is assigned.
50000L is a long literal. With a long operand, this multiplication uses long arithmetic. (long) 50000 * 50000 has the same effect.
Both int and long have finite ranges. Choose a type whose range is large enough for the calculation, not just the inputs.
Math methods
Java’s Math class provides numeric methods:
Math.min(a, b)returns the smaller value.Math.max(a, b)returns the larger value.Math.abs(value)returns the absolute value, except when that positive value exceeds the type’s range.Math.round(value)rounds to a whole number. With a double input it returns a long.
Math.round(3.6) is 4, while (int) 3.6 is 3. Halfway values round toward positive infinity: 3.5 rounds to 4, and -3.5 to -3.
For the int boundary, Math.abs(Integer.MIN_VALUE) stays negative because its positive counterpart does not fit in int.
Practice division and remainder together
To distribute 1001 whole items among 3 groups, give each group 1001 / 3, or 333, items. The remainder 1001 % 3 is 2. Two groups can receive one extra item.
Check the total with 333 * 3 + 2, which is 1001. Use a nonnegative item count and a positive group count.
Practice: calculate shares
There are 1850 + 755 items and 6 groups. Set those inputs in the workspace and calculate:
- The total.
- The whole-number share for each group.
- The remainder: the number of groups that receive one extra item.
- The reconstructed total.
Use variables and operators, rather than typing the answers. Expected results are 2605, 434, 1, and 2605.
Try different totals
Use the code cell above. Set practiceSecond to 0 so that practiceFirst is the total.
For the first row below, set practiceFirst to 1200 and practiceGroups to 4. Leave the calculation and print statements unchanged, then run the cell. It should print Share: 300 and Remainder: 0.
Repeat with the Total and Groups values from each remaining row. Compare the printed Share and Remainder with the table.
Total (practiceFirst) | Groups (practiceGroups) | Expected Share | Expected Remainder |
|---|---|---|---|
| 1200 | 4 | 300 | 0 |
| 2 | 5 | 0 | 2 |
| 0 | 4 | 0 | 0 |
| 1001 | 1 | 1001 | 0 |
The printed Reconstructed total should match Total each time. Keep practiceGroups greater than zero: integer division by zero causes an error.
Worked solution
Set practiceFirst to 1850 and practiceSecond to 755. Keep practiceGroups at 6.
The total is 2605. Integer division gives 434, and remainder gives 1. The check is 434 * 6 + 1, or 2605.
For another example, create a new code cell that declares a total of 2003 and a group count of 4. Print their quotient and remainder.
Check your understanding
Explain why 7 / 2 differs from 7 / 2.0, and why a cast before division differs from a cast afterward.
Check your distribution calculation with the boundary cases above. Explain how division and remainder reconstruct the total.
Enable JavaScript to run the Java notebook.