1Z0-808 · Question #85
Which code fragment cause a compilation error?
The correct answer is D. double y1 = 203.22; float flt = y1. Option D fails to compile because assigning a double variable directly to a float variable is a narrowing conversion - Java will not do this implicitly, since double (64-bit) is wider than float (32-bit) and data could be lost. Adding an explicit cast (float) y1 would fix it…
Question
Options
- Afloat flt = 100F;
- Bfloat flt = (float) 1_11.00;
- Cfloat flt = 100;
- Ddouble y1 = 203.22; float flt = y1;
- Eint y2 = 100; float flt = (float) y2;
How the community answered
(25 responses)- A4% (1)
- B12% (3)
- D80% (20)
- E4% (1)
Explanation
Option D fails to compile because assigning a double variable directly to a float variable is a narrowing conversion - Java will not do this implicitly, since double (64-bit) is wider than float (32-bit) and data could be lost. Adding an explicit cast (float) y1 would fix it.
Why the distractors compile successfully:
- A - The
Fsuffix explicitly declares the literal as afloat, so no conversion is needed. - B - The explicit
(float)cast handles the narrowing of thedoubleliteral; underscores in numeric literals (1_11) are valid since Java 7. - C - Assigning an
intliteral tofloatis a widening conversion, which Java allows implicitly. - E - The explicit
(float)cast legally narrows theintvariable tofloat.
Memory tip: Think "widening is free, narrowing needs a fee (a cast)" - Java freely promotes smaller types upward (int → float → double), but going down the hierarchy always requires an explicit cast or you'll pay with a compilation error.
Topics
Community Discussion
No community discussion yet for this question.