# Type Casting

Source: https://cca.twango.dev/AP-Computer-Science/type-casting

# Type Casting

## Widening conversions

Common widening paths are:

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

> [!warning] 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.

```java
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`:

```java
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](https://docs.oracle.com/javase/specs/jls/se17/html/jls-5.html#jls-5.1.2).

## Rounding

> [!warning] 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)](https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#round-double-).

Related: [[variables|Arithmetic]] · [[random|Random numbers]]
