Card 08/ 09
All 9 cards
ExerciseDifficulty: Intermediate1 min
Four Assignments: Which Compile, and Which Lose Something
Four lines. For each one, decide whether the compiler accepts it as written, and if it does, whether anything is lost. Write your four answers down before opening the reveal.
long a = 2_000_000;
int b = 3_000_000_000L;
int c = (int) 3.99;
double d = 7;Which of the four compile, and what does each one hold?
| Line | Compiles? | Result |
|---|---|---|
long a = 2_000_000; | Yes | Widening. a holds 2000000. |
int b = 3_000_000_000L; | No | Narrowing from long to int, and the value is past int's ceiling anyway. |
int c = (int) 3.99; | Yes | The cast overrules the check. c holds 3 — truncated, not rounded. |
double d = 7; | Yes | Widening. d holds 7.0. |
The one worth noticing is the third. A cast never rounds; it throws away everything after the point. (int) -3.99 is −3, not −4, because truncation goes towards zero rather than downwards.