A cast converts a value to another type: (int) 7.9 truncates to 7, and (double) 7 gives 7.0. To round a non-negative double x to the nearest int, use (int) (x + 0.5). An int holds only the values from Integer.MIN_VALUE to Integer.MAX_VALUE; arithmetic past either end overflows and wraps around with no error, and double arithmetic can carry small round-off errors.
Quick check
What is the value of 7 / 2 in Java, where both operands are int?Show answerHide answer
intdivision drops the fractional part.
What is the value of 7 / 2.0 in Java?Show answerHide answer
3.5. One operand is a
double, so the division is done indouble.
Know these already? Jump to the practice questions
What you'll be able to do
- Predict the value of an expression that uses
(int)or(double), including where the cast applies. - Use
(int) (x + 0.5)to round a non-negativedouble, and explain why(int) xalone truncates. - State the values of
Integer.MIN_VALUEandInteger.MAX_VALUE. - Determine the result when
intarithmetic overflows. - Explain why two
doubleresults that should be equal can differ slightly.
Key terms
Cast
An operator such as (int) or (double) written before a value to convert that value to the named type.
- In plain English
- A label that tells Java to treat the next value as a different type.
- Don't write
- "
(int) pricechanges the variablepriceinto anint."
Integer overflow
What happens when int arithmetic produces a result outside the int range: the result wraps around to the other end of the range.
- In plain English
- Counting past the largest
intlands you on the most negative one. - Don't write
- "Java throws an error when an
intgets too big."
Round-off error
A small difference between a double result and the exact answer, because a double stores most decimals as a close binary approximation.
- In plain English
- Decimal arithmetic on a computer is sometimes off in the last digits.
- Don't write
- "A
doublestores every decimal exactly."
What does a cast do?
A cast converts the value straight after it:
(int) 3.99is 3 and(int) -3.99is -3: the fractional part is cut off, moving toward zero.(double) 7is 7.0.
A cast applies before *, / and %, and only to the one value after it, so where you put it changes the answer:
| Expression | What happens | Value |
|---|---|---|
(double) 7 / 2 | 7.0 / 2 | 3.5 |
(double) (7 / 2) | int division first gives 3 | 3.0 |
Casting a variable does not change it. After double d = 4.8; and int n = (int) d;, n is 4 and d is still 4.8.
Learn this: casting is Java syntax, so it is not on the Java Quick Reference.
Key idea
A cast converts only the single value after it, so cast an operand before an int division, not the result after it.
Check yourself
Show answerHide answer
2.0. 9 / 4 is the int 2, and the cast then makes it 2.0.
How do you round instead of truncate?
(int) never rounds. To round a non-negative double x to the nearest whole number, add 0.5 first and then truncate:
x | x + 0.5 | (int) (x + 0.5) |
|---|---|---|
| 2.49 | 2.99 | 2 |
| 2.5 | 3.0 | 3 |
| 8.6 | 9.1 | 9 |
Adding 0.5 pushes any value whose fractional part is 0.5 or more past the next whole number, so truncating gives the rounded result.
The parentheses matter: (int) x + 0.5 casts first and then adds 0.5, giving a double such as 2.5.
The trick fails for negative values, because truncation moves toward zero: (int) (-2.7 + 0.5) is -2, but the nearest whole number is -3. For a negative x, use (int) (x - 0.5).
Check yourself
Show answerHide answer
- 6.5 + 0.5 is 7.0, which truncates to 7.
What are the limits of an int?
An int is stored in 32 bits, so it has a fixed range. Both ends are constants on the Java Quick Reference:
| Constant | Value |
|---|---|
Integer.MAX_VALUE | 2147483647 (2³¹ − 1) |
Integer.MIN_VALUE | -2147483648 (−2³¹) |
If int arithmetic goes past either end, the result overflows: it wraps around to the other end, and no error is reported. So Integer.MAX_VALUE + 1 is Integer.MIN_VALUE, and Integer.MIN_VALUE - 1 is Integer.MAX_VALUE. A product can overflow too: 1000000 * 1000000 evaluates to -727379968.
To work out an overflow, count steps past the end: going one past MAX_VALUE lands on MIN_VALUE, and each further step adds 1 from there.
Check yourself
Show answerHide answer
2147483647, which is Integer.MAX_VALUE: going one below the bottom wraps to the top.
Why are double results sometimes slightly off?
A double stores a number in binary, and most decimals, such as 0.1, have no exact binary form. Java stores the nearest value it can, so small errors can appear in arithmetic:
System.out.println(0.1 + 0.2);
This prints 0.30000000000000004, not 0.3. As a result, 0.1 + 0.2 == 0.3 is false.
To test whether two computed double values are equal, check that they are close instead: Math.abs(a - b) < 0.000001. Math.abs is on the Java Quick Reference.
Check yourself
Show answerHide answer
False. The sum is stored as 0.30000000000000004, which is not the stored value of 0.3.
Worked example 1: Truncate and round an average
Question: What is printed when this code segment runs?
int total = 48;
int count = 5;
double avg = (double) total / count;
int whole = (int) avg;
int nearest = (int) (avg + 0.5);
System.out.println(avg);
System.out.println(whole);
System.out.println(nearest);
What tells you the method
Casts and rounding on one value: trace each variable, noting its type.
Step 1: Trace the variables.
Line Variable Value 3 avg48.0 / 5 = 9.6 4 whole9 5 nearest(int) 10.1 = 10 WhyThe cast makes
total48.0 before the division, so the division keeps the fraction.Step 2: Print in order.
9.6, then 9, then 10.
Whywholetruncates 9.6, whilenearestadds 0.5 first, so it rounds up.
Check it
9.6 is nearer 10 than 9, so the rounded value 10 is right.
Answer
9.6 then 9 then 10, one per line.
Worked example 2: Count past the top of the int range
Question: What is printed when this code segment runs?
int x = Integer.MAX_VALUE - 2;
x = x + 5;
System.out.println(x);
What tells you the method
An int near Integer.MAX_VALUE with something added: check for overflow by counting steps past the end.
Step 1: Find the starting value.
xis 2147483647 − 2 = 2147483645.WhyThe subtraction stays inside the range, so nothing wraps yet.
Step 2: Count the five steps.
Two steps reach 2147483647, the third wraps to -2147483648, and two more reach -2147483646.
WhyOne step past
Integer.MAX_VALUElands onInteger.MIN_VALUE.
Check it
The true sum is 2147483650. The range holds 2³² = 4294967296 values, and 2147483650 − 4294967296 = −2147483646.
Answer
-2147483646
Worked example 3: Choose the rounding expression
Question: Which expression evaluates to the int nearest to x for every non-negative double x, with halves rounding up?
- A)
(int) x - B)
(int) x + 0.5 - C)
(int) (x + 1) - D)
(int) (x + 0.5)
What tells you the method
A rounding choice: test each option on values just below and just above a half, such as 2.2 and 2.7.
Step 1: Test 2.2, whose nearest
intis 2.A gives 2, B gives 2.5, C gives 3 and D gives 2.
WhyB is a
double, and C has moved up a whole number, so both fail here.Step 2: Test 2.7, whose nearest
intis 3.A gives 2 and D gives 3.
WhyA truncates, so it fails whenever the fractional part is 0.5 or more.
Check it
Test the boundary 2.5: D gives (int) 3.0, which is 3, so halves round up as required.
Answer
D
Your turn
Question: What is printed when this code segment runs?
int a = 7;
int b = 2;
System.out.println((double) a / b);
System.out.println((double) (a / b));
System.out.println((int) 3.5 * b);
Step 1: First line.
The cast makes
a7.0, then 7.0 / 2 is 3.5, so the first line is 3.5.Step 2: Your go: work out the second and third lines.
Show the full solutionHide the solution
Step 2. In line 4, a / b is the int 3, and the cast gives 3.0. In line 5, the cast applies to 3.5 only, giving 3, then 3 * 2 is 6.
Answer: 3.5 then 3.0 then 6, one per line.
Traps
Trap
(int) rounds a double to the nearest whole number.
It seems right because rounding is the usual way to turn a decimal into a whole number. But (int) truncates toward zero, so (int) 2.9 is 2 and (int) -2.9 is -2.
What is the value of (int) 5.99?
- The fractional part is cut off.
Trap
(double) (a / b) gives the exact quotient of two int values.
It seems right because the cast to double is in the expression. But the parentheses make the int division happen first, so the fraction is already gone; cast an operand instead, as in (double) a / b.
What is the value of (double) (9 / 2)?
4.0. 9 / 2 is the int 4.
Trap
Java stops with an error when an int result is too large.
It seems right because int division by zero does throw an exception. But overflow is silent: the result wraps around, so Integer.MAX_VALUE + 1 quietly becomes -2147483648.
Does Integer.MAX_VALUE + 1 throw an exception?
No. It evaluates to -2147483648, Integer.MIN_VALUE.
What's examined
On the AP® Computer Science A exam, Unit 1 casting and int range turn up in multiple-choice questions that ask for the value of an expression with a cast, whether a result is truncated or rounded, or what an overflowing calculation gives. In free response, you may need a cast to compute an average or round a result in a method you write.
Practice questions
- Recall What value does
(int) 9.99give?
- A) 9
- B) 9.0
- C) 9.99
- D) 10
Show answer
Answer: A. (int) truncates, so the .99 is cut off and the result is the int 9.
Why the others are wrong:
- B is a
double; an(int)cast gives anint. - C ignores the cast.
- D rounds, which
(int)never does.
- Apply What is printed when this code segment runs?
double d = -4.7;
int a = (int) d;
int b = (int) (d - 0.5);
System.out.println(a);
System.out.println(b);
Show answer
Answer: -4 then -5, one per line.
Marking points:
(int) -4.7truncates toward zero, giving −4.- −4.7 − 0.5 = −5.2, which truncates to −5, the nearest whole number to −4.7.
- Apply What is the value of
(double) (13 / 4)?
- A) 3
- B) 3.0
- C) 3.25
- D) 4.0
Show answer
Answer: B. 13 / 4 is the int 3, and the cast makes it 3.0.
Why the others are wrong:
- A forgets that the cast makes the result a
double. - C applies the cast before the division, which the parentheses prevent.
- D rounds 3.25 up, which neither division nor casting does.
- Exam-style What is printed when this code segment runs?
int m = Integer.MAX_VALUE;
m = m * 2;
System.out.println(m);
Show answer
Answer: -2
Marking points:
- The true product is 2 × 2147483647 = 4294967294, which is past the top of the range.
- Wrapping subtracts 2³² = 4294967296, giving −2.
- Exam-style This code segment is meant to print the average of the scores, rounded to the nearest whole number, which is 8.
totalandcountmust stayintvariables, and only one line may change. Give the number of the line that stops it working.
1: int total = 47;
2: int count = 6;
3: double avg = total / count;
4: int rounded = (int) (avg + 0.5);
5: System.out.println(rounded);
Show answer
Answer: Line 3.
Marking points:
total / countisintdivision, giving 7, soavgis 7.0 and the code prints 7.- Changing line 3 to
(double) total / countgives 7.833333333333333, which rounds to 8.
- Exam-style
aandbaredoublevalues that each come from several calculations. Which test is the safest way to check whether they are equal?
- A)
a == b - B)
(int) a == (int) b - C)
Math.abs(a - b) < 0.000001 - D)
a - b == 0
Show answer
Answer: C. It allows for round-off error by checking that the values are very close.
Why the others are wrong:
- A can be
falsefor values that should be equal, such as 0.1 + 0.2 and 0.3. - B throws away the fractions, so 2.1 and 2.9 would count as equal.
- D is the same test as A, with the same round-off problem.
- Recall What is the name for what happens when
intarithmetic goes pastInteger.MAX_VALUEand wraps around?
Show answer
Answer: Overflow.
Marking points:
- The result wraps to the other end of the range, and no error is reported.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
(int)truncates toward zero;(double)turns anintinto adouble.- A cast converts only the value right after it, so
(double) a / bdivides indoublebut(double) (a / b)does not. - For a non-negative
x,(int) (x + 0.5)rounds to the nearestint. intvalues run from -2147483648 to 2147483647, and going past either end wraps around silently.doublearithmetic can be slightly off, so compare computeddoublevalues with a tolerance.