Java, Software Development

Java Primitive Float And Double – What’s the difference?

The Java primitives float and double are floating-point values. They are similar, but not the same. In this post, we’ll talk about these two primitives and some values of these types.

Java Primitive Floats

By default, any floating-point literal value in Java is of a double type. Consider the following codes.

The codes on line 2 compile successfully. But the ones on line 5 causes a compile-time error.

Why is that so? That’s by design. Floats are inaccurate values especially after calculating them.

 

Consider the following codes with compilation error from the Eclipse IDE

8-8-2016 10-37-30 AM

Floating-point literal 13.1 is of type double by default

To fix this problem, place “f” or “F” at the end of the literal.

[wp_ad_camp_2]

8-8-2016 10-44-22 AM

We can assign integral literals to variables of either float or double type without any special suffixes.

8-8-2016 10-47-48 AM

[wp_ad_camp_3]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like