Ssg Ssg - 2 months ago 20
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

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 : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

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.