Card 08/ 09

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.

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 int's ceiling 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.

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.