Card 06/ 09
All 9 cards
ConceptDifficulty: Intermediate1 min
Why the Compiler Refuses an Assignment You Have Not Run Yet
You put a double into an int and the build fails before anything has run. The value was 3.0, which fits in an int perfectly well.
Total.java:4: error: incompatible types: possible lossy conversion from double to int
int rounded = average;
^Java is statically typed: every variable's type is fixed where it is declared, and the compiler checks every assignment against it without running a line. It is not asking whether your value fits. It is asking whether every possible value of the source type fits the target.
| Assignment | Accepted? | Why |
|---|---|---|
int into long | Yes | Every int fits in a long — widening |
char into int | Yes | Every char fits — widening |
long into int | No | Most long values do not fit — narrowing |
double into int | No | The fractional part has nowhere to go — narrowing |
A cast is you overruling that check: int rounded = (int) average; compiles, truncates towards zero, and is now your responsibility. The cast does not convert safely — it tells the compiler you have thought about the loss.
What you get in exchange for declaring types is that a whole class of mistake becomes impossible to ship. A misspelled field, a method called on the wrong type, a string handed where a number was wanted: all of them fail on your machine rather than on a customer's.