Similarities :
1) Both double and float are used to represent real numbers in Java i.e. numbers with fractions or decimal points.2) Both double and float are approximate types, they are not precise.
3) You should use logical operator e.g. > or < to compare both float and double variables, instead of = and != because they are not precise.
See this article for more details about comparing float and double variables in Java.
You can also see classic Core Java Volume 1 - Fundamentals by Cay S. Horstmann to learn more about similarities and differences between a float and a double data type in Java. One of the best book to learn Java currently.
Difference between float vs doubles in Java
Here is some key differences between float and double in Java :1) The double data type is more precise than float in Java.
2) double takes more space than float in Java. double needs 64-bit storage compare to 32-bit storage of float data type.
3) double has a higher range than float, sure because it got more bits to store data.
4) float uses 1 bits for sign, 8 bits for exponent and 23 bits for mantissa, while double uses 1 bits for sign, 11 bits for exponent and 52 bits for mantissa.
5) By default, floating point numbers are double in Java. In order to store them into float variable, you need to cast them explicitly or suffix with 'f' or 'F' as shown below :
public static final float PIE = 3.14; // compile time error
Use cast
public static final float PIE = (float) 3.14;
or suffix 'f' or 'F'
public static final float PIE = 3.14f; public static final float GRAVITY = 9.8F;
As I said before, you can also take a look at Core Java Volume 1 - Fundamentals by Cay S. Horstmann to learn more about similarities and differences between a float and a double data type in Java. One of the better book to learn Java in the market.

When to use double and float in Java?
Though both can be used to represent floating point numbers, there are couple of things you can consider to choose between double and float. Though both are approximate types, If you need more precise and accurate result then use double. Use float if you have memory constraint because it take almost half as much space as double. If your numbers cannot fit in range offered by float then use double. Though be careful with floating point calculation and representation, don't use double or float for monetary calculation, instead use BigDecimal.That's all on difference between float and double in Java. Remember, by default floating point numbers are double in Java, if you want to store them into float variable, you need to either cast them explicitly or suffixed them using 'f' or 'F' character.
It's also best practice to choose a data type which take less storage if it's sufficient for data you are storing, so choose float over double if you are happy with precision and range, double is more accurate then float though.
No comments:
Post a Comment