nerdexam
Oracle

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…

Data Types and Operators

Question

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?

Options

  • Alines 5 and 7
  • Bline 7
  • Clines 6 and 8
  • Dline 5

How the community answered

(69 responses)
  • A
    4% (3)
  • B
    1% (1)
  • C
    9% (6)
  • D
    86% (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; - assigning float to int is 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 though long has more bits, float → long is still a narrowing conversion in Java's type hierarchy. An explicit cast is required.

Why lines 5 and 7 are fine:

  • float fValue = 120; - 120 is an int literal. int → float is a widening conversion and is allowed implicitly. No error here.
  • double dValue = fValue; - float → double is 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

#type casting#implicit conversion#primitive types#widening/narrowing

Community Discussion

No community discussion yet for this question.

Full 1Z0-811 Practice