Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
- The casting operators
(int)and(double)convert betweendoubleandintvalues. - Casting a
doubleto aninttruncates: the digits to the right of the decimal point are dropped. - Some code widens
intvalues todoubleautomatically (assignment to adouble, or anintmeeting adoublein an operator). - A cast has higher precedence than
*,/and+and applies to what is immediately to its right. (int) (x + 0.5)rounds a non-negativedouble;(int) (x - 0.5)rounds a negative one.Integer.MAX_VALUEandInteger.MIN_VALUEare the largest and smallestint. Anintuses 4 bytes, so it must be in that range, inclusive.- Integer overflow: the result is an
intin range but not necessarily what you expected. No exception is thrown. - Round-off error: a
doublemore precise than can be stored is rounded to a representable value. Useintvalues to avoid it.
Key relationships
| Expression | Value | Reason |
|---|---|---|
(int) 3.99 |
3 |
truncation |
(int) -3.99 |
-3 |
truncation toward zero |
(double) 7 |
7.0 |
widening by cast |
(double) 7 / 2 |
3.5 |
cast on 7 first, then a double division |
(double) (7 / 2) |
3.0 |
the integer division is done first |
(int) 2.5 * 2 |
4 |
cast applies to 2.5 only |
(int) (2.5 * 2) |
5 |
bracket first |
(int) (87.5 + 0.5) |
88 |
rounds a non-negative value |
(int) (-3.6 - 0.5) |
-4 |
rounds a negative value |
Integer.MAX_VALUE + 1 |
Integer.MIN_VALUE |
overflow wraps around |
0.1 + 0.2 |
0.30000000000000004 |
round-off error |
Assumptions and conventions
- The only primitive types used are
int,doubleandboolean. - Brackets around the expression decide how far a cast reaches.
- Overflow throws no exception; the program carries on with a wrong value.
- The exam gives no calculator: do not expect to compute a wrapped overflow value digit by digit, but know that the result is in range and unexpected.
Mistakes to avoid
- Treating
(int)as rounding. It truncates. - Putting the cast in the wrong place, so a fraction is lost before the cast happens.
- Using
(int) (x + 0.5)for negative numbers. Usex - 0.5. - Expecting an exception on overflow.
- Thinking
Integer.MAX_VALUE + 1is bigger. It wraps to the smallest value. - Believing a
doubleshows every decimal exactly. - Adding a needless cast to store an
intin adouble.
Quick self-check
- What is
(int) 9.8? (9) - What is
(double) 5 / 4, and what is(double) (5 / 4)? (1.25 and 1.0) - Round 6.5 to the nearest
intusing a cast. ((int) (6.5 + 0.5) is 7) - What is the value of
Integer.MAX_VALUE + 1? (Integer.MIN_VALUE, by overflow) - Why might
0.1 + 0.2not print exactly 0.3? (Round-off error in the stored double values.)
Next: practice questions.