---
title: "Primitive Casting | FiveStudy"
description: "Widening is free, narrowing costs the fraction — and cast placement decides the answer."
url: https://fivestudy.com/guides/primitive-casting
---

[AP Computer Science A](https://fivestudy.com/ap-computer-science-a) · Study guide

# Primitive Casting

[Figure: FiveStudy]

FiveStudy

AP® Computer Science A · Using Objects and Methods

AP® Computer Science A · Using Objects and Methods

# Primitive *Casting*

How to convert between int and double: the casting operators, truncation, automatic widening, where a cast applies inside an expression, and how to round a double to the nearest integer.

1. Why Cast 2. Casting to int 3. Casting to double 4. Where a Cast Applies 5. Automatic Widening 6. Rounding

Big Picture

Programs often need a value of one type when they have a value of another: a real-number average from integer scores, or a whole number of items from a `double` measurement. The **casting operators** `(int)` and `(double)` convert a value from one primitive type to the other. Casting a `double` to an `int` truncates, discarding the digits after the decimal point. Some conversions from `int` to `double` happen automatically. And by adding or subtracting 0.5 before casting, a program can round to the nearest integer.

## 1 Why Programs Cast

Each value in Java has a type, and the type controls what operations do. Sometimes the natural type of the data is not the type an operation needs. Quiz scores are whole numbers, so they are `int` values, but their average usually has a fractional part. A measurement such as 7.8 meters is a `double`, but the number of whole meters is an `int`. Casting bridges these situations by converting a value to a different type exactly where the conversion is needed.

A cast is written by putting the target type in parentheses before a value: `(double) sum` or `(int) length`. The cast does not change the variable; it produces a new value of the requested type for use in the expression. After `double avg = (double) sum / count;`, the variable `sum` is still an `int` with its original value.

| Expression | Value | Explanation |
| --- | --- | --- |
| `(int) 9.99` | 9 | Digits after the decimal point are truncated |
| `(int) -9.99` | −9 | Truncation moves toward zero |
| `(double) 9` | 9.0 | Converts the int to a double |
| `(double) 9 / 2` | 4.5 | Cast applies to 9 before dividing |
| `(double) (9 / 2)` | 4.0 | Integer division happens first |
| `(int) (9.6 + 0.5)` | 10 | Rounds a non-negative value |
| `(int) (-9.6 - 0.5)` | −10 | Rounds a negative value |

## 2 Casting a double to an int

The casting operator `(int)` converts a `double` value to an `int` value. Casting a `double` value to an `int` value causes the digits to the right of the decimal point to be **truncated**: simply removed. `(int) 7.9` is 7, not 8. For negative numbers, truncation moves toward zero, so `(int) -7.9` is −7.

Truncation is exactly right when you want "how many whole units": the number of complete laps in 7.9 laps, or the whole-dollar part of a price. It is the wrong tool when you want the *closest* whole number, which is a rounding problem handled in the last section.

Because a cast to `int` can lose information, Java never performs it silently. Storing a `double` in an `int` variable without a cast is a compile-time error; the explicit `(int)` tells the compiler, and every reader, that losing the fraction is intended.

**Figure 1.** Casting a `double` to an `int` drops the digits to the right of the decimal point, which moves positive and negative values toward zero.

Worked Example 1 Basic casts

### What Each Cast Produces

Predict each value.

Code

```
System.out.println((int) 7.9);
System.out.println((int) 7.1);
System.out.println((int) -7.9);
System.out.println((double) 5);
System.out.println((int) 0.99);
```

Output

```
7
7
-7
5.0
0
```

1. 1 **`(int) 7.9` and `(int) 7.1`.** Both truncate to 7; the fractional part is removed, not rounded.
2. 2 **`(int) -7.9`.** Truncation moves toward zero: −7, not −8.
3. 3 **`(double) 5`.** The `int` becomes the `double` 5.0.
4. 4 **`(int) 0.99`.** Truncates to 0, even though 0.99 is almost 1.

**Result:** The values are 7, 7, −7, 5.0, and 0. Casting to `int` removes everything after the decimal point.

Common Mistake 1 · Expecting (int) to Round

`(int) 2.99` is 2. A cast to `int` always truncates, even when the fractional part is .99. If the nearest integer is wanted, add 0.5 first (or subtract 0.5 for negative values) and then cast.

## 3 Casting an int to a double

The casting operator `(double)` converts an `int` value to a `double` value: `(double) 5` is 5.0. No information is lost, since every integer in the `int` range can be represented as a `double`.

The most important use of `(double)` is to avoid integer division. When both operands of `/` are `int` values, the fractional part of the quotient is discarded. Casting one of them to `double` makes the division real. This is the standard way to compute averages, percentages, and rates from integer counts while keeping the counts themselves as `int` variables.

Worked Example 2 Averages

### Averaging int Values With a Cast

A student has 4 quiz scores with a sum of 349. Compute the average as a `double`.

Code

```
int sum = 349;
int count = 4;
double wrong = sum / count;
double right = (double) sum / count;
System.out.println(wrong);
System.out.println(right);
```

Output

```
87.0
87.25
```

1. 1 **Without a cast.** `349 / 4` is integer division, 87, stored as 87.0.
2. 2 **With a cast.** `(double) sum / count` is 349.0 / 4 = 87.25.
3. 3 **Why cast rather than change types?** The sum and count really are whole numbers, so they should stay `int`. The cast converts only at the point where real division is needed.

**Result:** The correct average is 87.25. Casting one operand to `double` right where you divide keeps the variables' natural types and gives the real quotient.

## 4 Where a Cast Applies

A casting operator has higher precedence than the arithmetic operators, so it applies only to the value immediately to its right. In `(double) a / b`, the cast converts `a`, and then the division is real. In `(double) (a / b)`, the parentheses make the integer division happen first, and only the already-truncated result is converted, which is too late to recover the fraction.

When writing a cast, ask exactly which value needs to change type and place the cast directly in front of it, using parentheses when the cast should apply to a whole expression. When reading a cast, find the value it touches and evaluate the expression step by step, tracking the type at each step.

**Figure 2.** A cast applies to the value immediately to its right. Casting one operand before dividing gives real division; casting the result of an integer division is too late to recover the fraction.

Worked Example 3 Cast placement

### Three Places to Put the Cast

Predict each line.

Code

```
int a = 7;
int b = 2;
System.out.println((double) a / b);
System.out.println((double) (a / b));
System.out.println(a / (double) b);
System.out.println((int) (a / 2.0));
```

Output

```
3.5
3.0
3.5
3
```

1. 1 **Line 1.** The cast applies to `a` first: 7.0 / 2 = 3.5.
2. 2 **Line 2.** The parentheses force `a / b` first: integer division gives 3, then the cast gives 3.0.
3. 3 **Line 3.** Casting either operand is enough: 7 / 2.0 = 3.5.
4. 4 **Line 4.** 3.5 is computed, then truncated to 3.

**Result:** The results are 3.5, 3.0, 3.5, and 3. A cast must come before the division to make the division real, as Figure 2 shows.

Common Mistake 2 · Casting After the Division

`(double) (sum / count)` looks like it should give a real average, but the integer division inside the parentheses has already discarded the fraction. Cast an operand *before* dividing: `(double) sum / count`.

## 5 Automatic Widening

Some code causes `int` values to be automatically cast, or **widened**, to `double` values. This happens when an `int` is stored in a `double` variable, when an arithmetic operation combines an `int` with a `double`, and when an `int` is passed to a method parameter of type `double`. In each case Java quietly performs the conversion because nothing can be lost.

Narrowing, from `double` to `int`, never happens automatically. That asymmetry is a safety feature: the compiler insists that any conversion that could discard information be written out explicitly.

**Figure 3.** Some code causes `int` values to be automatically cast (widened) to `double` values. Going the other way can lose information, so it requires an explicit cast.

| Situation | Automatic or cast? | Example |
| --- | --- | --- |
| Storing an int in a double variable | Automatic (widening) | `double d = 4;` → 4.0 |
| Arithmetic with one int and one double | Automatic (widening) | `4 * 0.5` → 2.0 |
| Storing a double in an int variable | Cast required | `int n = (int) 4.9;` → 4 |
| Getting real division from two ints | Cast one operand | `(double) a / b` |

Worked Example 4 Automatic widening

### Where Java Converts for You

Which conversions happen automatically? Predict the output.

Code

```
int laps = 3;
double distance = laps;
double perLap = 2.5;
System.out.println(distance);
System.out.println(laps * perLap);
System.out.println(laps + 1.0);
```

Output

```
3.0
7.5
4.0
```

1. 1 **Assignment.** `double distance = laps;` widens the `int` 3 to 3.0 automatically.
2. 2 **Mixed arithmetic.** In `laps * perLap`, the `int` is widened to 3.0 before multiplying: 7.5.
3. 3 **Adding a double literal.** `laps + 1.0` widens 3 and gives 4.0.
4. 4 **The reverse never happens silently.** `int n = perLap;` would not compile; it needs `(int) perLap`.

**Result:** The output is 3.0, 7.5, and 4.0. Java widens `int` to `double` whenever needed, because no information is lost.

Common Mistake 3 · Thinking Widening Happens Before Integer Division

In `double r = 7 / 2;`, widening happens only when the finished value is stored. The division `7 / 2` is computed first with two `int` values, giving 3, which is then widened to 3.0. Widening changes the type of a value; it never re-runs the arithmetic that produced it.

## 6 Rounding With Casts

Values of type `double` can be rounded to the nearest integer by `(int) (x + 0.5)` for non-negative numbers, or `(int) (x - 0.5)` for negative numbers. Adding 0.5 pushes any value whose fractional part is at least .5 past the next whole number, so the truncation that follows lands on the nearest integer. For negative numbers the logic is mirrored: subtracting 0.5 moves the value away from zero before truncation moves it back toward zero.

The addition must be inside the parentheses. `(int) x + 0.5` casts first and then adds 0.5, producing a `double` such as 4.5 rather than a rounded integer. Rounding is especially important when a calculation that should produce a whole number comes out as something like 1998.9999999999998 because of round-off error; truncating that value would give the wrong integer, while rounding gives the intended one.

**Figure 4.** Adding 0.5 pushes any value at or past the halfway point over the next whole number, so truncating afterward rounds to the nearest integer. Negative values subtract 0.5 instead.

| x | x + 0.5 | (int) (x + 0.5) | nearest integer? |
| --- | --- | --- | --- |
| 2.2 | 2.7 | 2 | yes |
| 2.5 | 3.0 | 3 | yes |
| 2.8 | 3.3 | 3 | yes |
| 7.0 | 7.5 | 7 | yes |

Worked Example 5 Rounding

### Rounding to the Nearest Integer

Round 4.5, 4.49, and −2.7 to the nearest integer using casts.

Code

```
double p = 4.5;
double q = 4.49;
double r = -2.7;
System.out.println((int) (p + 0.5));
System.out.println((int) (q + 0.5));
System.out.println((int) (r - 0.5));
```

Output

```
5
4
-3
```

1. 1 **4.5.** 4.5 + 0.5 = 5.0, which truncates to 5.
2. 2 **4.49.** 4.49 + 0.5 = 4.99, which truncates to 4.
3. 3 **−2.7.** For a negative value, subtract 0.5: −2.7 − 0.5 = −3.2, which truncates toward zero to −3, the nearest integer.
4. 4 **Parentheses matter.** `(int) p + 0.5` would truncate first and then add, producing the `double` 4.5.

**Result:** The results are 5, 4, and −3. Add 0.5 for non-negative values and subtract 0.5 for negative values, then cast, with the addition inside the parentheses.

Worked Example 6 Round-off and casting

### Converting Dollars to Cents

A price of 19.99 dollars should become 1999 cents. Predict what the first attempt stores, then fix it.

First attempt

```
double price = 19.99;
int cents = (int) (price * 100);
System.out.println(price * 100);
System.out.println(cents);
```

Output

```
1998.9999999999998
1998
```

1. 1 **The product is not exactly 1999.** Because many decimal values cannot be stored exactly as a `double`, 19.99 × 100 is computed as 1998.9999999999998.
2. 2 **Truncation makes it worse.** Casting to `int` drops the fraction, giving 1998, one cent short.
3. 3 **Round instead of truncating.**

   Fixed

   ```
   double price = 19.99;
   int cents = (int) (price * 100 + 0.5);
   System.out.println(cents);
   ```

   Output

   ```
   1999
   ```

**Result:** Truncating produced 1998; rounding with `+ 0.5` before the cast produces 1999. When a `double` should be a whole number, round it rather than truncating it.

Common Mistake 4 · Using +0.5 on Negative Numbers

`(int) (-2.7 + 0.5)` is `(int) -2.2`, which is −2, but −2.7 is closer to −3. For negative values use `(int) (x - 0.5)`: −3.2 truncates to −3.

### Four Habits for Casting

#### 1. (int) Truncates

It chops off the fraction and moves toward zero; it never rounds.

#### 2. Cast Before You Divide

Put (double) on an operand, not on an integer quotient.

#### 3. Widening Is Free

int becomes double automatically; double to int always needs a cast.

#### 4. Round Deliberately

(int) (x + 0.5) for non-negative x, (int) (x - 0.5) for negative x.

Core Synthesis

The casting operators `(int)` and `(double)` convert a `double` value to an `int` value or vice versa. Casting a `double` to an `int` truncates the digits to the right of the decimal point. Some code causes `int` values to be automatically cast (widened) to `double` values. A cast applies to the value immediately after it, so it must come before a division to make that division real. Values of type `double` can be rounded to the nearest integer by `(int) (x + 0.5)` for non-negative numbers or `(int) (x - 0.5)` for negative numbers.

FiveStudy AP® Computer Science A Study Guide · Using Objects and Methods · Primitive Casting Back to top ↑
