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.
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.
1Why 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 |
2Casting 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.
double to an int drops the digits to the right of the decimal point, which moves positive and negative values toward zero.What Each Cast Produces
Predict each value.
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);
7
7
-7
5.0
0
- 1
(int) 7.9and(int) 7.1. Both truncate to 7; the fractional part is removed, not rounded. - 2
(int) -7.9. Truncation moves toward zero: −7, not −8. - 3
(double) 5. Theintbecomes thedouble5.0. - 4
(int) 0.99. Truncates to 0, even though 0.99 is almost 1.
int removes everything after the decimal point.(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.
3Casting 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.
Averaging int Values With a Cast
A student has 4 quiz scores with a sum of 349. Compute the average as a double.
int sum = 349;
int count = 4;
double wrong = sum / count;
double right = (double) sum / count;
System.out.println(wrong);
System.out.println(right);
87.0
87.25
- 1Without a cast.
349 / 4is integer division, 87, stored as 87.0. - 2With a cast.
(double) sum / countis 349.0 / 4 = 87.25. - 3Why 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.
double right where you divide keeps the variables' natural types and gives the real quotient.4Where 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.
Three Places to Put the Cast
Predict each line.
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));
3.5
3.0
3.5
3
- 1Line 1. The cast applies to
afirst: 7.0 / 2 = 3.5. - 2Line 2. The parentheses force
a / bfirst: integer division gives 3, then the cast gives 3.0. - 3Line 3. Casting either operand is enough: 7 / 2.0 = 3.5.
- 4Line 4. 3.5 is computed, then truncated to 3.
(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.
5Automatic 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.
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 |
Where Java Converts for You
Which conversions happen automatically? Predict the output.
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);
3.0
7.5
4.0
- 1Assignment.
double distance = laps;widens theint3 to 3.0 automatically. - 2Mixed arithmetic. In
laps * perLap, theintis widened to 3.0 before multiplying: 7.5. - 3Adding a double literal.
laps + 1.0widens 3 and gives 4.0. - 4The reverse never happens silently.
int n = perLap;would not compile; it needs(int) perLap.
int to double whenever needed, because no information is lost.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.
6Rounding 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.
| 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 |
Rounding to the Nearest Integer
Round 4.5, 4.49, and −2.7 to the nearest integer using casts.
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));
5
4
-3
- 14.5. 4.5 + 0.5 = 5.0, which truncates to 5.
- 24.49. 4.49 + 0.5 = 4.99, which truncates to 4.
- 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.
- 4Parentheses matter.
(int) p + 0.5would truncate first and then add, producing thedouble4.5.
Converting Dollars to Cents
A price of 19.99 dollars should become 1999 cents. Predict what the first attempt stores, then fix it.
double price = 19.99;
int cents = (int) (price * 100);
System.out.println(price * 100);
System.out.println(cents);
1998.9999999999998
1998
- 1The product is not exactly 1999. Because many decimal values cannot be stored exactly as a
double, 19.99 × 100 is computed as 1998.9999999999998. - 2Truncation makes it worse. Casting to
intdrops the fraction, giving 1998, one cent short. - 3Round instead of truncating.
Fixed
double price = 19.99; int cents = (int) (price * 100 + 0.5); System.out.println(cents);Output1999
+ 0.5 before the cast produces 1999. When a double should be a whole number, round it rather than truncating it.(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.
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.