Command Palette

Search for a command to run...

PHASE 1Beginner ~28 min· topic 7 of 14

Topic 1.7

Arithmetic Operators, Integer Division and Remainder

In one line

Java's arithmetic operators are +, -, *, / and %, plus ++, -- and compound forms like +=. Between integers, / throws away the remainder and % gives it back with the sign of the left operand, and integer division by zero throws an exception while decimal division doesn't.

Think of it like this

Sharing 7 sweets fairly between 2 children. Each child gets 3 whole sweets (7 / 2 = 3) and 1 sweet is left over (7 % 2 = 1). Nobody gets half a sweet, because sweets are whole things. Java's integer division works the same way: whole numbers in, whole numbers out, and % tells you what's left.

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

Operator
A symbol that does something to values, like + (add) or % (remainder).
Operand
A value an operator works on. In 7 / 2, the operands are 7 and 2.
Expression
Any piece of code that produces a value, like price * qty + 5.
Integer division
Dividing two whole numbers and keeping only the whole part of the answer.
Remainder (modulo)
What's left over after integer division. % gives it: 7 % 2 is 1.
Precedence
The rule for which operators run first when there are no brackets, like multiplication before addition.
Associativity
The direction operators of equal precedence run in. Arithmetic runs left to right.
Increment
Increasing a variable by one, written ++.
Side effect
A change to a variable caused while an expression is being evaluated, like the ++ inside a[i++].

Step by step

01The five arithmetic operators

+ add, - subtract, * multiply, / divide, % remainder. Their result type follows the promotion rules from Topic 1.6: two ints give an int, an int and a double give a double.

+ has a second job: if either operand is a String, it joins text (Topic 1.10). That's why brackets matter in "sum: " + (a + b).

02Integer division throws the fraction away

7 / 2 is 3. The true answer, 3.5, is truncated toward zero, so -7 / 2 is -3, not -4. This is not rounding: 99 / 100 is 0.

To get the decimal answer, make one operand a decimal *before* dividing: 7 / 2.0, 7.0 / 2 or (double) a / b.

Math.floorDiv(-7, 2) rounds toward negative infinity instead, giving -4. It matters when you divide negative numbers into buckets, such as converting negative timestamps to days.

03The remainder and its sign

Java guarantees (a / b) * b + a % b == a for integers. Since / truncates toward zero, the remainder takes the sign of the left operand: -7 % 2 is -1, because -7 / 2 is -3 and -3 × 2 + (-1) = -7.

This catches people writing n % 2 == 1 to test for odd numbers: for negative odd numbers n % 2 is -1. Test n % 2 != 0 instead.

Math.floorMod(a, b) always has the sign of b, so with a positive b it's never negative. That's what you want for circular indexes: Math.floorMod(index - 1, size).

The remainder and its signdiagram
Rendering diagram…

04Everyday uses of / and %

Splitting a quantity into units: 3725 seconds is 3725 / 3600 = 1 hour, 3725 % 3600 / 60 = 2 minutes, 3725 % 60 = 5 seconds.

Taking numbers apart: n % 10 is the last digit and n / 10 removes it. Repeat that in a loop to sum or reverse digits (Phase 2, and the DSA course at /dsa).

Checking divisibility: n % k == 0 means k divides n. Even numbers: n % 2 == 0. Wrapping around: (i + 1) % size cycles 0, 1, …, size-1, 0.

05Precedence and evaluation order

From high to low: unary + - ++ --, then * / %, then binary + -. Equal precedence runs left to right, so 2 * 3 / 4 is 6 / 4 = 1, but 2 / 4 * 3 is 0 * 3 = 0. The order changes the answer when integer division is involved.

Separately from precedence, Java always evaluates operands left to right (JLS §15.7). In f() + g() * h(), f() is called first even though the multiplication is done first. C leaves this unspecified; Java fixes it.

06++ and --: prefix vs postfix

int b = a++; means: remember the old a, add one to a, and the expression's value is the old one. int d = ++c; adds one first and gives the new value.

i = i++; is the classic trap: i++ evaluates to the old value (10) and increments i to 11, then the assignment stores the old value 10 back. Net effect: nothing.

Rule of thumb: use ++ as a statement on its own (count++;) or in a for header. Don't use it inside larger expressions where readers must simulate the order.

++ and --: prefix vs postfixdiagram
Rendering diagram…

07Compound assignment and Math helpers

x += 5 is shorthand for x = (T) (x + 5), and the same goes for -=, *=, /=, %=. Besides being shorter, the left side is evaluated only once, which matters for arr[next()] += 1.

Math.pow(a, b) returns a double; Math.sqrt, Math.abs, Math.max, Math.min are what you'd expect. For integer powers in tight code, multiply directly or use shifts for powers of two.

Try it yourself

  1. 1

    Predict the signs

    Write down the values of -9 / 4, -9 % 4, 9 % -4 and Math.floorMod(-9, 4), then add them to the first example and check. (Answers: -2, -1, 1, 3.)

  2. 2

    Convert minutes

    Change totalSeconds to 100000 in the third example. Predict the hours, minutes and seconds (27h 46m 40s), then add a days calculation with / 86400.

  3. 3

    Divide by zero two ways

    Add System.out.println(10.0 / 0); and then System.out.println(10 / 0);. The first prints Infinity; the second compiles (the compiler doesn't reject it) but throws ArithmeticException when it runs.

Code & diagrams

Division and remainder with positive and negative numbers New tab
Sign in to run this example in your browser.

Expected output

7 / 2   = 3
7 % 2   = 1
-7 / 2  = -3
-7 % 2  = -1
7 % -2  = 1
floorDiv(-7, 2) = -4
floorMod(-7, 2) = 1
7.0 / 2 = 3.5
5.5 % 2 = 1.5
99 / 100 = 0
Prefix vs postfix increment New tab
Sign in to run this example in your browser.

Expected output

a=6 b=5
c=6 d=6
after i = i++, i=10
x=5 y=8
Precedence and practical / and % New tab
Sign in to run this example in your browser.

Expected output

14
20
3
1
0
1h 2m 5s
last digit 7, rest 482
4827 is even? false
Math.pow(2, 10) = 1024.0
2 ^ 10 = 8  (XOR, not power!)
average 7 vs 7.5
Wrapping around a circle with floorMod New tab
Sign in to run this example in your browser.

Expected output

3 days after Tue:  Fri
3 days before Tue: Sat
(1 - 3) % 7 = -2

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

Divide an integer by zero

Share 10 apples between kids = 0 children.

Main.javawhole filejava
public class Main {
    public static void main(String[] args) {
        int apples = 10;
        int kids = 0;
        System.out.println(apples / kids);
    }
}
terminal
$ javac Main.java
java Main
── what you'll see ──
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)

Break #2

Use ^ as power

Compute an area with int area = side ^ 2; for side = 5.

terminal
$ javac Main.java
java Main
── what you'll see ──
7

Myth vs fact

Myth

-7 / 2 is -4 because it rounds down.

Fact

Java's integer division truncates toward zero, so it's -3. Math.floorDiv gives -4.

Myth

% is the mathematical modulo and is never negative.

Fact

It's a remainder whose sign follows the left operand. Use Math.floorMod for a non-negative result with a positive divisor.

Myth

i++ is faster than ++i.

Fact

For a primitive used as a statement, both compile to the same iinc instruction. Choose by meaning, not speed.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    idiv and ldiv throw on zero, but there's also an overflow case: Integer.MIN_VALUE / -1 overflows and returns Integer.MIN_VALUE (no exception), and Integer.MIN_VALUE % -1 is 0. The JLS spells this out in §15.17.2.

  • ▸

    JIT compilers turn division by a constant into a multiply and shift (division is 20–40 cycles on many CPUs, multiplication 3–4), and x % 8 into x & 7 only when it can prove x is non-negative, because the results differ for negative x.

  • ▸

    Java fixes left-to-right operand evaluation (JLS §15.7), so i = i++ + i++ has a defined result in Java (for i = 1 it's 3), unlike C, where it's undefined behaviour. Defined still doesn't mean readable.

  • ▸

    Math.pow is a floating-point function: (int) Math.pow(10, 2) is 100, but for large exponents results can be off by one in the last digit compared with exact integer arithmetic. Use integer multiplication or BigInteger.pow when exact results matter.

Remember this

  1. 1

    Integer division (/ with two integer operands) truncates toward zero: 7 / 2 is 3 and -7 / 2 is -3. If either operand is a double, you get decimal division: 7 / 2.0 is 3.5.

  2. 2

    Remainder % satisfies (a / b) * b + (a % b) == a, so its sign follows the left operand: -7 % 3 is -1 and 7 % -3 is 1. When you need a result that's never negative (for example wrapping around a circular array), use Math.floorMod(-7, 3), which gives 2.

  3. 3

    Division by zero: with integers, / and % throw ArithmeticException: / by zero. With double, 1.0 / 0 is Infinity and 0.0 / 0 is NaN (Topic 1.4).

  4. 4

    Precedence: *, /, % happen before + and -; operators of equal precedence run left to right. 2 + 3 * 4 is 14 and 10 - 4 - 3 is 3. Use parentheses whenever the order isn't obvious to a reader.

  5. 5

    Increment and decrement: ++i adds one and gives the new value; i++ adds one but gives the old value. On a line of its own they behave identically. Inside a bigger expression they differ, and i = i++; famously leaves i unchanged.

  6. 6

    ^ is not power in Java; it's bitwise XOR (Topic 1.9), so 2 ^ 10 is 8. Use Math.pow(2, 10) (returns double 1024.0) or, for powers of 2, 1 << 10. The Math class also has abs, max, min, sqrt, floorDiv and floorMod.

Explain it without notes

01

What do / and % produce for -7 and 2, and why?

02

What's the difference between i++ and ++i, and why does i = i++ leave i unchanged?

03

Why does 10 / 0 throw an exception while 10.0 / 0 doesn't?

04

How would you safely compute the previous index in a circular buffer of size n?

Practice

01

Given 1234 paise, print it as rupees and paise: 12 rupees 34 paise.

02

Print the sum of the digits of 9875 using only / and % (no Strings).

03

Print whether -7, 0 and 12 are odd, using a test that works for negative numbers.

Trade-offs

  • ↔

    Integer division is fast and exact for whole quantities, but silently drops fractions; decide deliberately whether you want truncation, floor, or a decimal result.

  • ↔

    % is cheap and familiar but its negative results surprise people; Math.floorMod is clearer for wrap-around logic at a tiny cost.

  • ↔

    ++ inside expressions saves a line but makes code harder to read and review; most style guides allow it only as a standalone statement or in loop headers.

Done when you can

  • I can predict / and % for any mix of positive and negative integers.

  • I know when Java does integer versus decimal division and how to force decimal division.

  • I know integer division by zero throws and decimal division doesn't.

  • I can explain prefix vs postfix ++ and the i = i++ puzzle.

  • I use Math.pow, not ^, for powers and know operator precedence.