Card 08/ 09
Practice: Which Numeric Assignments Compile
Four lines; for each, whether it compiles and whether anything is lost.
Widening assignments compile on their own, narrowing ones need a cast (a type in brackets, such as (int), that forces the conversion), and a cast truncates. Using those rules, decide for each of the four lines below whether the compiler accepts it as written, and if it does, what the variable holds. Write all four answers down before opening the answer.
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 the ceiling of an int 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. |
Look closely at 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.
← → move through sections and cards