Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › JAVA FUNDAMENTALS
The variable distanceKm stores the value 12.75 as a double. If you try to assign it directly to wholeKm, which has type int, Java rejects the assignment before the program runs. Java checks the source and target types, not just whether this particular value seems safe to use.
double distanceKm = 12.75;
int wholeKm = distanceKm; // compile errorA double can contain a fractional part, but an int cannot. The conversion from double to int is therefore a narrowing conversion, because the target type may hold less information than the source type. Java requires you to write an explicit cast to show that you accept the possible loss.
Which assignment can store distanceKm in wholeKm without a compile error?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Add the cast before distanceKm to make Java perform the narrowing conversion. The value placed in wholeKm is 12. The cast removes the fractional part by moving toward zero, so it does not round 12.75 up to 13.
double distanceKm = 12.75;
int wholeKm = (int) distanceKm;
System.out.println(distanceKm); // 12.75
System.out.println(wholeKm); // 12The cast changes the value produced for the assignment, but it does not change distanceKm. That variable still contains 12.75, while wholeKm contains the separate int value 12. A conversion creates a value for the target variable; it does not rewrite the source variable.
Now wholeKm has the int value 12. Assigning it to restoredKm, whose type is double, is widening conversion. Every int value can be represented as a double, so Java performs this conversion automatically.
double distanceKm = 12.75;
int wholeKm = (int) distanceKm;
double restoredKm = wholeKm;
System.out.println(restoredKm); // 12.0The result is 12.0, not 12.75. Widening changes the representation of the value 12 so it can be stored as a double, but it does not look back at distanceKm or recover information that is no longer in wholeKm.
After the full conversion chain, what value is stored in restoredKm?
double distanceKm = 12.75;
int wholeKm = (int) distanceKm;
double restoredKm = wholeKm;Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
The complete chain keeps the original and converted values in separate variables. distanceKm remains 12.75 because conversions do not alter the source variable. wholeKm stores 12 after the narrowing cast, and restoredKm stores 12.0 after the automatic widening conversion.
double distanceKm = 12.75;
int wholeKm = (int) distanceKm;
double restoredKm = wholeKm;
System.out.println(distanceKm); // 12.75
System.out.println(wholeKm); // 12
System.out.println(restoredKm); // 12.0