✏️ Explanatory Question

[Primitive Values, Wrapper Classes, Types and Casting]

The following statement will generate a compile time error. This can be rectified in 2 different ways, without losing precision of price. Write these statements:
float price = 17.99;

👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

float price = 17.99;
Correct Statements:
float price = 17.99f;
float price = (float) 17.99;

Why Error Occurs:

In Java, decimal numbers like:

17.99

are treated as double by default.

So the statement:

float price = 17.99;

tries to assign a double value to a float variable.

This causes a:

Compile-Time Error (possible loss of precision)

Two Ways to Fix It:

Method Explanation
Using 'f' suffix Tells Java that the number is float type explicitly
Type casting Converts double value to float manually

Method 1: Using 'f' suffix

float price = 17.99f;

Here, f indicates float literal.

Method 2: Type Casting

float price = (float) 17.99;

Here, the double value is explicitly converted to float.

Important Concept:

Default decimal → double float requires → 'f' suffix OR casting

Conclusion:

  • Error occurs due to type mismatch (double → float)
  • It can be fixed using:
  • ✅ float price = 17.99f;
  • ✅ float price = (float) 17.99;