Ssg Ssg - 1 year ago 103
Java Question

Declaring float f=12.1 in java shows error

When i declare the below statement it shows error,

float f=12.1; //Type mismatch: cannot convert from double to float

But I can store the same value from user using nextFloat();

Sorry for the basic question, I couldnt understand the difference

Answer Source

You're missing the f at the end:

float f=12.1f; 

If you just put "12.1", that would be a double (64 bits). And you're trying to fit that "double" (64 bits) into a float (32 bits)=won't work. If you just need a float (32 bits), you have to tell java you want that. Thus the f at the end.

Excerpt from :

A floating-point literal is of type float if it ends with the letter F or f; otherwise its type is double and it can optionally end with the letter D or d.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download