CCA Guide
Type Casting

Type Casting

Curated by Last modified: 1 min read

View Markdown

Widening conversions

Common widening paths are:

byte → short → int → long → float → double
char → int → long → float → double

Correction to the original notes

There is no widening step short → char. Widening to a floating-point type can also lose precision; it does not always preserve every digit.

int myInt = 10;
double myDouble = myInt; // Widening: an explicit cast is unnecessary.

Narrowing conversions

Use an explicit cast for conversions such as double to int:

double value = 10.9;
int truncated = (int) value; // 10

The original example declared two variables named myInt and cast int to double, which is widening. The examples above correct both issues.

Source: Java conversions §5.1.2–5.1.3.

Rounding

Correction to the original shortcut

(int) (value + 0.5) only works as the intended nearest-integer shortcut for nonnegative, in-range values. A cast truncates toward zero, so negative values break that rule.

Use Math.round(value) for nearest-integer rounding with halfway cases toward positive infinity. For a double, its result is a long.

Source: Math.round(double).

Related: Arithmetic · Random numbers

Linked to this page