In Java, which three are valid declarations for a float variable among the following candidates?

Difficulty: Medium

Correct Answer: 1, 3, 6

Explanation:

Introduction / Context:Java's float is a 32-bit IEEE 754 type. Literal rules matter: decimal literals are double by default unless suffixed with F/f, whereas integer and hex integer literals can be assigned to float via widening conversion.

Given Data / Assumptions:

  • Candidates: f1 = -343; f2 = 3.14; f3 = 0x12345; f4 = 42e7; f5 = 2001.0D; f6 = 2.81F.
  • We check only compile-time validity without explicit casts.

Concept / Approach:Rules: decimal floating-point literals are double unless suffixed F; assigning a double to float without cast is illegal. Integer literals (decimal/hex/octal) can widen to float. Scientific notation without F is double. Suffix D marks an explicit double literal.

Step-by-Step Solution:

f1 = -343; → int literal to float via widening → valid.f2 = 3.14; → double literal to float without cast → invalid.f3 = 0x12345; → hex int to float via widening → valid.f4 = 42e7; → double literal (scientific) to float without F → invalid.f5 = 2001.0D; → explicit double to float without cast → invalid.f6 = 2.81F; → float literal with F suffix → valid.

Verification / Alternative check:Adding explicit casts (e.g., (float)3.14) would make f2/f4/f5 compile, but the original forms do not.

Why Other Options Are Wrong:They include at least one invalid assignment per the rules above.

Common Pitfalls:Forgetting the F suffix for decimal float literals; assuming all numeric literals can be assigned without casts.

Final Answer:1, 3, 6

More Questions from Language Fundamentals

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion