Card 08/ 09

ExerciseDifficulty: Intermediate1 min

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.

java
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?
The four assignments, with what the compiler does and what survives
LineCompiles?Result
long a = 2_000_000;YesWidening. a holds 2000000.
int b = 3_000_000_000L;NoNarrowing from long to int, and the value is past the ceiling of an int anyway.
int c = (int) 3.99;YesThe cast overrules the check. c holds 3: truncated, not rounded.
double d = 7;YesWidening. 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.