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: What usually goes wrong. What you see What caused it How to fix it --- --- --- 5 and 2 print 3.0 instead of 3.5 Both operands were int, so the division truncated before the result ever
Challenge: True Average of Two