nerdexam
Oracle

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…

Working With Java Data Types

Question

Which code fragment cause a compilation error?

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)
  • A
    4% (1)
  • B
    12% (3)
  • D
    80% (20)
  • E
    4% (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 F suffix explicitly declares the literal as a float, so no conversion is needed.
  • B - The explicit (float) cast handles the narrowing of the double literal; underscores in numeric literals (1_11) are valid since Java 7.
  • C - Assigning an int literal to float is a widening conversion, which Java allows implicitly.
  • E - The explicit (float) cast legally narrows the int variable to float.

Memory tip: Think "widening is free, narrowing needs a fee (a cast)" - Java freely promotes smaller types upward (intfloatdouble), but going down the hierarchy always requires an explicit cast or you'll pay with a compilation error.

Topics

#type conversion#float/double types#narrowing conversion#compilation errors

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice