Integer vs Double Division
Part of: Primitive Types
Division Depends on Types The / operator behaves very differently depending on the types of its operands. This is one of the most tested and most error-prone ideas in Unit 1. Integer Division When both operands are int , Java performs integer division : it divides and truncates (throws away) any fractional part, it does not round. The remainder is simply discarded. 7 / 2 is 3 because 2 goes into 7 three full times. Truncation always moves toward zero, so -7 / 2 is -3. Double Division If at least one operand is a double , Java performs floating-point division and keeps the fractional part: Even one double "promotes" the whole expression to double arithmetic. This is called type promotion . A Classic Trap Consider: Why? The right side 7 / 2 is computed first using int division (both are ints), giving 3. Only then is 3 stored into the double, becoming 3.0. The variable's type does not change how the expression is evaluated, the operand types do. To get 3.5, make an operand a double before dividing: Why It Matters Computing averages, percentages, and rates almost always requires double division. Forgetting to promote an operand silently produces wrong, truncated answers. Always ask: ar
Challenge: True Average of Two