Card 06/ 09

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.

text
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.

Which numeric assignments the compiler accepts on their own
AssignmentAccepted?Why
int into longYesEvery int fits in a long — widening
char into intYesEvery char fits — widening
long into intNoMost long values do not fit — narrowing
double into intNoThe 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.