Casting Between Types

Part of: Primitive Types

Why Cast? Sometimes you need to convert a value from one primitive type to another. A cast explicitly tells Java to treat a value as a different type. The syntax is the target type in parentheses before the value: int to double (Widening) Converting an int to a double is a widening conversion. It is safe and Java does it automatically (implicitly), but you may cast explicitly for clarity: double to int (Narrowing) Converting a double to an int is a narrowing conversion. It can lose information, so Java requires an explicit cast . Casting to int truncates : it drops the fractional part, it does NOT round: The Most Important Use: Forcing Double Division Recall that int / int truncates. Casting one operand to double fixes this: The cast (double) total makes the left operand a double, so the division is double division. Watch precedence: a cast binds tighter than /, so (double) total / count casts total first, then divides. Compare: Rounding by Hand Since casting truncates, round a positive double by adding 0.5 first: Casting is essential for averages, percentages, and controlling exactly how numbers convert. Always remember: double-to-int truncates toward zero.

Challenge: Percentage Score