Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Arithmetic Operators in Java: Division, Overflow, Promotion
Java arithmetic is straightforward until operands have different types or values reach their limits. Integer division truncates toward zero, % keeps the dividend’s sign, and ordinary int and long overflow wraps around.
Introduction
Addition, subtraction, multiplication, division, and remainder operate on numeric values such as int, long, float, and double. The result depends on the operand types. For example, 7 / 2 is 3, while 7.0 / 2 is 3.5.
Floating-point values use binary representation, so many decimal fractions such as 0.1 are approximations. For decimal money, use BigDecimal constructed from a string or store integer minor units such as cents. Specify the rounding rule when a calculation needs rounding.
The examples below cover division, remainder, overflow, type promotion, and floating-point behavior. They also show when Math.addExact() or BigDecimal is useful.
Choosing a numeric type
| Need | Suitable choice | Watch for |
|---|---|---|
| Whole-number counts and indexes | int or long |
Ordinary overflow wraps; use exact methods if overflow should fail. |
| Approximate measurements or scientific calculations | float or double |
Binary floating-point cannot exactly represent every decimal fraction. |
| Decimal amounts such as currency | BigDecimal or integer minor units |
Define when and how to round. |
For decimal calculations, build a BigDecimal from a string. This small example calculates a total with an explicit rounding rule:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class MoneyExample {
public static void main(String[] args) {
BigDecimal price = new BigDecimal("19.99");
BigDecimal taxRate = new BigDecimal("0.0825");
BigDecimal total = price.multiply(BigDecimal.ONE.add(taxRate))
.setScale(2, RoundingMode.HALF_UP);
System.out.println(total); // 21.64
}
}
RoundingMode.HALF_UP is only an example; use the rule your application requires. The Java API recommends the string constructor when starting with a decimal literal, because new BigDecimal(0.1) captures the approximation already stored in the double.
Operator precedence and associativity
graph TD
A["Expression: a + b * c - d / e % f"] --> B["1. * / % (left-to-right)"]
B --> C["2. + - (left-to-right)"]
C --> D["3. Assignment = (right-to-left)"]
E["Parentheses () override precedence"] --> A
F["Unary + - have higher precedence than * /"] --> A
Runnable arithmetic results
public class ArithmeticResults {
public static void main(String[] args) {
int intOverflow = Integer.MAX_VALUE + 1;
int intUnderflow = Integer.MIN_VALUE - 1;
long longOverflow = Long.MAX_VALUE + 1L;
int whole = 7;
double fraction = 2.5;
System.out.println("7 / 2 = " + (7 / 2));
System.out.println("-7 / 2 = " + (-7 / 2));
System.out.println("7.0 / 2 = " + (7.0 / 2));
System.out.println("-7 % 4 = " + (-7 % 4));
System.out.println("7 % -4 = " + (7 % -4));
System.out.println("-7 % -4 = " + (-7 % -4));
System.out.println("Integer.MAX_VALUE + 1 = " + intOverflow);
System.out.println("Integer.MIN_VALUE - 1 = " + intUnderflow);
System.out.println("Long.MAX_VALUE + 1 = " + longOverflow);
System.out.println("int + double = " + (whole + fraction));
}
}
Save this as ArithmeticResults.java, then run javac ArithmeticResults.java && java ArithmeticResults.
| Expression | Result | What it shows |
|---|---|---|
7 / 2 |
3 |
Integer division truncates toward zero. |
-7 / 2 |
-3 |
Negative integer division also truncates toward zero. |
7.0 / 2 |
3.5 |
A floating-point operand makes the result floating-point. |
-7 % 4 |
-3 |
The remainder has the dividend’s sign. |
7 % -4 |
3 |
A negative divisor does not make the remainder negative. |
-7 % -4 |
-3 |
With a negative dividend, the remainder is negative. |
Integer.MAX_VALUE + 1 |
-2147483648 |
Ordinary int overflow wraps. |
Integer.MIN_VALUE - 1 |
2147483647 |
Ordinary int underflow wraps. |
Long.MAX_VALUE + 1L |
-9223372036854775808 |
Ordinary long overflow wraps. |
int + double (7 + 2.5) |
9.5 (double) |
Binary numeric promotion converts the int operand to double. |
Java’s % operator returns a remainder, not a floor-based modulo. For a positive divisor, Math.floorMod(-7, 4) is 1, while -7 % 4 is -3.
Failure scenarios
| Scenario | Problem | Response |
|---|---|---|
| Integer division | Truncates toward zero, so 7 / 2 is 3. |
Use a floating-point operand for an approximate fractional result. |
| Negative remainder | % can return a negative value when the dividend is negative. |
Use Math.floorMod() when floor-based modulo is required. |
| Integer overflow | Ordinary int and long arithmetic wraps without throwing. |
Check bounds or use methods such as Math.addExact(). |
| Division by zero | Integer division throws ArithmeticException. |
Validate the divisor before dividing. |
| Mixed numeric types | Binary numeric promotion determines the expression type. | Check the result type and cast only when narrowing is intentional. |
Arithmetic choices
| Operation | Behavior | Result or failure |
|---|---|---|
+, -, * on int or long |
Ordinary fixed-width integer arithmetic | Overflow wraps. |
/ on integers |
Truncates toward zero | Division by zero throws ArithmeticException. |
% on integers |
Returns the remainder of truncating division | A nonzero result has the dividend’s sign; divisor zero throws ArithmeticException. |
Math.addExact() |
Checks addition for overflow | Throws ArithmeticException if the result is out of range. |
Security notes
Integer overflow can invalidate a bounds check such as offset + length > buffer.length. Check ranges without overflowing, or use Math.addExact() when an overflow should fail. Validate divisors that come from input. Use established cryptographic libraries for cryptographic calculations; floating-point arithmetic is not suitable for them.
Pitfalls
- Integer division truncates toward zero:
7 / 2is3, not3.5. - The remainder follows the dividend’s sign:
-7 % 4is-3, not1. - Ordinary overflow wraps:
Integer.MAX_VALUE + 1isInteger.MIN_VALUE. - Mixed operands undergo numeric promotion: adding an
intto adoubleproduces adoubleresult. - Compound assignment does not detect overflow: with
int x = Integer.MAX_VALUE;,x += 1wraps toInteger.MIN_VALUE.
Quick recap checklist
- Confirm whether each division should truncate or produce an approximate decimal result.
- Check both operands’ signs when using
%; useMath.floorMod()only when its floor-based result is intended. - Decide whether
intorlongoverflow may wrap or must throw. - Check the result type when an expression mixes numeric types.
- Use
BigDecimalfrom decimal strings or integer minor units for money, with an explicit rounding rule. - Validate divisors that can be zero.
Interview questions
Further reading
- Oracle Java Tutorial: Operators covers arithmetic and other operators.
- Java SE 27 Language Specification, division and remainder defines integer division and
%behavior. - Java SE 27 Language Specification, integer operations describes overflow behavior.
- Java SE 27 Language Specification, binary numeric promotion defines mixed-type arithmetic.
- Java SE 27 BigDecimal API documents decimal arithmetic and rounding.
- BigDecimal for Financial Calculations explains when to use
BigDecimal. - Integer Overflow and Math.addExact covers checked arithmetic.
- Type Conversion and Casting explains numeric conversions.
Conclusion
The operators are easy to use once you track operand types, signs, and range limits. Integer division truncates toward zero, % follows the dividend’s sign, and ordinary int or long overflow wraps.
Use Math.addExact() when overflow should throw, and use BigDecimal or integer minor units for money. Set the rounding rule explicitly. For the next step, see relational and logical operators and Java bitwise operators.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.
ArrayList in Java
Compare ArrayList's Java SE 27 contract with OpenJDK 27 growth behavior, capacity hints, operation costs, fail-fast iterators, and bounded concurrency options.