1Z0-811 · Question #48
Given the code fragment: 5. float fValue = 120; 6. int iValue = fValue; 7. double dValue = fValue; 8. long lValue = fValue; At which line does a compilation error occur?
The correct answer is D. line 5. The provided answer key appears to be incorrect. Option C (lines 6 and 8) is the actual correct answer based on Java's type conversion rules. Here's the full breakdown: Why lines 6 and 8 fail: int iValue = fValue; - assigning float to int is a narrowing conversion (float → int…
Question
Options
- Alines 5 and 7
- Bline 7
- Clines 6 and 8
- Dline 5
How the community answered
(69 responses)- A4% (3)
- B1% (1)
- C9% (6)
- D86% (59)
Explanation
The provided answer key appears to be incorrect. Option C (lines 6 and 8) is the actual correct answer based on Java's type conversion rules. Here's the full breakdown:
Why lines 6 and 8 fail:
int iValue = fValue;- assigningfloattointis a narrowing conversion (float → int loses the fractional part and possibly magnitude). Java requires an explicit cast:int iValue = (int) fValue;long lValue = fValue;- same issue. Even thoughlonghas more bits,float → longis still a narrowing conversion in Java's type hierarchy. An explicit cast is required.
Why lines 5 and 7 are fine:
float fValue = 120;-120is anintliteral.int → floatis a widening conversion and is allowed implicitly. No error here.double dValue = fValue;-float → doubleis also widening. Perfectly legal with no cast needed.
Java's widening order to memorize:
byte → short → int → long → float → double
Assignments going left to right (widening) are implicit. Going right to left (narrowing) requires an explicit cast.
Memory tip: "Wide is fine, narrow needs a sign" - widening is silent, narrowing needs a visible (cast) to remind you data may be lost.
If this question came from a practice exam or textbook, the answer key has a typo - C is correct.
Topics
Community Discussion
No community discussion yet for this question.