What is float in Java?

t0mkaka picture t0mkaka · Feb 22, 2011 · Viewed 405.8k times · Source

I wrote this code:

float b = 3.6;

and I get this:

Error:Unresolved compilation problem: 
    Type mismatch: cannot convert from double to float

Why? Whats the definition of float?

Answer

Nicolas picture Nicolas · Feb 22, 2011

In Java, when you type a decimal number as 3.6, its interpreted as a double. double is a 64-bit precision IEEE 754 floating point, while floatis a 32-bit precision IEEE 754 floating point. As a float is less precise than a double, the conversion cannot be performed implicitly.

If you want to create a float, you should end your number with f (i.e.: 3.6f).

For more explanation, see the primitive data types definition of the Java tutorial.