Unit 02 · lesson

Integer Division Will Betray a Bad Mental Model

Predict this before running it:

void main() {
    int completed = 7;
    int total = 10;
    double rate = completed / total;
    IO.println(rate);
}

Many people predict 0.7 because rate is a double.

Java evaluates the right side first.

completed / total
     7    /  10

Both operands are integers, so Java performs integer division. The result is 0. Only then is that result widened and stored as 0.0 in the double variable.

The destination type does not travel backward in time and change how the division was evaluated.

Repair the operation, not the symptom

One solution:

double rate = (double) completed / total;

Now one operand is a double, so the numeric operation uses floating-point division and produces 0.7.

Another:

double completed = 7;
int total = 10;
double rate = completed / total;

Both can be correct. Which is clearer depends on what completed represents throughout the program.

Operator order matters too

Predict:

int result = 2 + 3 * 4;

Multiplication occurs before addition, so the result is 14.

If the intended grouping is different, show it:

int result = (2 + 3) * 4;

Now the result is 20.

Parentheses are not merely for making the compiler happy. They can make the programmer's model visible.

Percentages expose type mistakes quickly

Suppose a test suite passes 18 of 24 cases.

Wrong:

double percent = 18 / 24 * 100;

The first division becomes 0 before multiplication.

Better:

double percent = (double) 18 / 24 * 100;

Expected result: 75.0.

Build a prediction matrix

Before executing, predict each result and state the type of the intermediate division.

IO.println(5 / 2);
IO.println(5.0 / 2);
IO.println(5 / 2.0);
IO.println((double) 5 / 2);
IO.println(5 / 2 * 2);
IO.println(5 * 2 / 2);

Then run the code in the Java Playground and record actual results.

For any wrong prediction, do not write "Java is weird." Identify the exact operation whose operand types you misread.

Apply it to a real decision

Write a compact-source program that receives fixed values for passed and total, computes a pass percentage, and prints both the raw fraction and percentage.

Use at least these test cases:

passedtotalexpected
71070.0%
1425.0%
050.0%
55100.0%

What should happen if total is zero? Do not silently ignore the question. You have discovered a failure condition that control flow will handle in a later unit.

The transferable idea

The important rule is larger than integer division:

Expressions have their own evaluation rules and intermediate types.

When a final value looks wrong, trace the expression from the inside out instead of staring only at the destination variable.