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.

published: reading time: 12 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

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

  1. Integer division truncates toward zero: 7 / 2 is 3, not 3.5.
  2. The remainder follows the dividend’s sign: -7 % 4 is -3, not 1.
  3. Ordinary overflow wraps: Integer.MAX_VALUE + 1 is Integer.MIN_VALUE.
  4. Mixed operands undergo numeric promotion: adding an int to a double produces a double result.
  5. Compound assignment does not detect overflow: with int x = Integer.MAX_VALUE;, x += 1 wraps to Integer.MIN_VALUE.

Quick recap checklist

  • Confirm whether each division should truncate or produce an approximate decimal result.
  • Check both operands’ signs when using %; use Math.floorMod() only when its floor-based result is intended.
  • Decide whether int or long overflow may wrap or must throw.
  • Check the result type when an expression mixes numeric types.
  • Use BigDecimal from decimal strings or integer minor units for money, with an explicit rounding rule.
  • Validate divisors that can be zero.

Interview questions

1. What is the result of `7 / 2` in Java?
The result is `3` (integer division). Java truncates toward zero, so fractional parts are discarded. Use `7.0 / 2` or cast to double for `3.5`.
2. What is integer overflow and how does it manifest in Java?
Ordinary `int` addition wraps from `Integer.MAX_VALUE` to `Integer.MIN_VALUE` without throwing. Use `Math.addExact()` when that overflow should raise `ArithmeticException`.
3. What is the difference between `a % b` and `Math.floorMod(a, b)`?
`%` returns a remainder whose nonzero result has the dividend's sign. For example, `-7 % 4` is `-3`. `Math.floorMod(-7, 4)` is `1`; with a negative divisor, `floorMod` can return a negative value.
4. What is operator precedence in Java?
Multiplicative operators (`*`, `/`, `%`) have higher precedence than additive operators (`+`, `-`). Parentheses `()` override precedence. Unary operators have even higher precedence. Use parentheses to make intent clear rather than relying on precedence rules.
5. Why should you avoid floating-point for financial calculations?
Floating-point (`double`, `float`) cannot exactly represent many decimal values (e.g., `0.1`). Calculations accumulate errors. For monetary values, use `java.math.BigDecimal` which provides arbitrary precision and control over rounding.
6. What happens when you divide two integers in Java?
Integer division truncates toward zero. `7 / 2` yields `3`, not `3.5`. The fractional part is silently discarded. If floating-point result is needed, at least one operand must be floating-point: `7.0 / 2` or `(double) 7 / 2`.
7. What is the result of `10 % 3` and why?
`10 % 3` yields `1`. Modulo returns the remainder after integer division. The remainder is always less than the divisor (3) and carries the sign of the dividend (10), which is positive, so result is `1`.
8. What is type promotion in Java arithmetic?
Java applies binary numeric promotion to arithmetic operands. For example, `int + double` converts the `int` operand to `double`, and the result is `double`. Unary `+` and `-` promote `byte`, `short`, and `char` to `int` first.
9. What does `Math.addExact()` protect against that regular `+` does not?
`Math.addExact()` throws `ArithmeticException` when overflow occurs, while `+` silently wraps. For example, `Integer.MAX_VALUE + 1` wraps to `Integer.MIN_VALUE`, but `Math.addExact(Integer.MAX_VALUE, 1)` throws. Use it in security-critical counter increments.
10. What is the difference between prefix (`++i`) and postfix (`i++`) increment?
Both increment `i` by 1. Prefix (`++i`) returns the incremented value; postfix (`i++`) returns the original value. In standalone statements like `i++;` or `++i;`, both have the same effect. In expressions like `x = ++i;` vs `x = i++;`, `++i` assigns the incremented value, `i++` assigns the original.
11. How does compound assignment like `x *= y` handle overflow differently from `x = x * y`?
For `int` and `long`, both `x *= y` and `x = x * y` perform the same overflow-wrapping behavior. However, compound assignment first widening-converts `x` to the type of the expression before the operation, which can cause unexpected results with mixed types: `int x = 1; x *= 1.5;` gives `x = 1` (truncated), not a compile error.
12. What is the result of `100 / 0` and `100.0 / 0`?
`100 / 0` throws `ArithmeticException` (integer division by zero). `100.0 / 0` yields `Infinity` (no exception). Floating-point supports infinity, negative zero, and NaN as special values per IEEE 754.
13. What is the result of `5 / 2` in Java and how do you get a decimal result?
`5 / 2` yields `2` (integer division truncates toward zero). To get a decimal result, at least one operand must be a floating-point type: `5.0 / 2` or `(double) 5 / 2` yields `2.5`.
14. What happens when `long` overflows in Java?
Ordinary `long` arithmetic wraps too. `Long.MAX_VALUE + 1L` evaluates to `Long.MIN_VALUE`. Use `Math.addExact()` when overflow should throw `ArithmeticException`.
15. What is the difference between `Math.floorMod()` and the `%` operator?
`%` uses truncating division, so `-7 % 4` is `-3`. `Math.floorMod(-7, 4)` is `1`, while `Math.floorMod(-7, -4)` is `-3`. Its result follows the divisor's sign when nonzero.
16. What does the unary minus operator do to integer types?
The unary minus operator negates the value. For `int`, `-Integer.MIN_VALUE` still overflows to `Integer.MIN_VALUE` (since +2147483648 exceeds `int` range). For `long`, `-Long.MIN_VALUE` similarly overflows. The result is always within the type's range.
17. Why does `double result = 1.0 / 3.0;` not give exactly 0.333333...
A `double` uses binary floating-point, so `1.0 / 3.0` is an approximation. `BigDecimal` can represent decimal inputs such as `0.1` exactly when constructed from a string, but one third still needs a rounding rule because its decimal expansion does not terminate.
18. What is the difference between `i += 1` and `i = i + 1`?
For primitive numeric types, `i += 1` and `i = i + 1` are equivalent for simple types like `int`. However, `i += 1.5` (mixed types) first widens `i` to `double`, performs the addition, then truncates back to `int` when assigning. `i = i + 1.5` would not compile.
19. What is the associativity of arithmetic operators in Java?
All binary arithmetic operators (`+`, `-`, `*`, `/`, `%`) are left-associative: `a - b - c` is parsed as `(a - b) - c`. This matters for floating-point where `a - b - c` may differ from `a - (b - c)` due to rounding errors.
20. What is the result of `3 + 4 * 5` and how does operator precedence affect it?
The result is `23`, not `35`. Multiplication has higher precedence than addition, so `4 * 5` is computed first (giving `20`), then `3 + 20 = 23`. Use parentheses if you need addition first: `(3 + 4) * 5 = 35`.

Further reading

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-abstract-classes #java #java-fundamentals

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.

#java-array-basics #java #java-fundamentals

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.

#java-arraylist #java #java-fundamentals