AP® Computer Science A · Unit 1 · Topic 1.5
Casting Between int and double
Casting tells Java to treat a value as a different type for one expression: (double) forces real division with decimals, and (int) chops off any decimal part without rounding.
Java decides how to do division by looking at the types involved before it calculates anything. If both operands are ints, Java performs integer division and throws away the remainder, no matter what you do with the result afterward. A cast changes this at the source: writing (double) in front of one operand converts that value to a double before the division happens, so the whole expression becomes real-number division and keeps the decimal part.
Casting a double to an int works the opposite direction, and it does something more brutal than rounding. (int) truncates: it deletes everything after the decimal point and keeps only the whole number part, regardless of whether the discarded part was .1 or .9. There is no rounding logic involved at all, which is why 7.9 becomes 7, not 8.
This matters because Unit 1 is built on the idea that values carry a type, and operations behave according to the types present, not according to what answer you wanted. Casting is how you override that default behavior for a single expression without changing the variable's declared type permanently. The next ideas in the unit, like calling methods on objects and understanding references, all depend on this same habit: check the type first, then predict the behavior.
Key terms
- Cast
- An explicit instruction, written as (type), that converts a value to a different type for one expression.
- Truncation
- Discarding the decimal part of a number entirely, without rounding, when converting a double to an int.
- Integer division
- Division between two ints in Java that drops any remainder and returns only the whole number quotient.
- Type promotion
- Converting a value to a wider type, such as int to double, so an operation can produce a decimal result.
Watch it explained
- How it worksHow does a cast to double change the arithmetic before the division ever happens?
- Worked exampleFind the value of (double) 7 / 2 and compare it with (double) (7 / 2).
- How it worksHow does casting a double to an int chop off the decimal instead of rounding it?
- Worked exampleFind what (int) (2.99·100) actually gives, and why the answer is not 299.
- Common mistakeWhy isn't casting a double to an int the same as rounding to the nearest whole number?
Check yourself
End of topic.