Card 06/ 09
Static Typing: Widening, Narrowing and Casts
A double holding 3.0 fits in an int, and the compiler still refuses to put it there.
Java is statically typed: every variable's type is fixed where it is declared, and the compiler checks every assignment against it before anything runs. An assignment is accepted on its own only if every possible value of the source type fits the target; otherwise you need a cast.
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;
^The compiler is not asking whether your value fits. It is asking whether every possible double fits in an int, and a fractional part has nowhere to go.
| 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.
← → move through sections and cards