Videos
From my textbook:
When you write a floating-point literal in your program code, Java assumes it to be of the double data type. A double value is not compatible with a float variable because a double can be much larger or smaller than the allowable range for a float. As a result, code such as the following will cause an error:
Example 1:
float number; number = 23.5; //Error!
You can force a double to be treated as a float, by suffixing it with the letter F or f. The preceding code can be rewritten in the following manner to prevent an error:
Example 2:
float number; number = 23.5F; //This will work. ===================================================
I can't figure out why example 1 produces an error. Why is 23.5 considered a double? I thought it was a float.
AFAIK, float numbers are precise up to 7 decimal digits of accuracy. 23.5 only has 1 decimal digit. What am I not understanding? I thought by typing 'float number;' you are declaring the number variable to be a float. Why would you need the extra step of adding an F?
Thanks
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.
Make it
float b= 3.6f;
A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d
- Read More