According to this java.sun page ==
is the equality comparison operator for floating point numbers in Java.
However, when I type this code:
if(sectionID == currentSectionID)
into my editor and run static analysis, I get: "JAVA0078 Floating point values compared with =="
What is wrong with using ==
to compare floating point values? What is the correct way to do it?
Foating point values are not reliable, due to roundoff error.
As such they should probably not be used for as key values, such as sectionID. Use integers instead, or
long
ifint
doesn't contain enough possible values.The following automatically uses the best precision:
Of course, you might choose more or less than 5 ULPs (‘unit in the last place’).
If you’re into the Apache Commons library, the
Precision
class hascompareTo()
andequals()
with both epsilon and ULP.If you *have to* use floats, strictfp keyword may be useful.
http://en.wikipedia.org/wiki/strictfp
In one line answer I can say, you should use:
To make you learned more about using related operators correctly, I am elaborating some cases here: Generally, there are three ways to test strings in Java. You can use ==, .equals (), or Objects.equals ().
How are they different? == tests for the reference quality in strings meaning finding out whether the two objects are the same. On the other hand, .equals () tests whether the two strings are of equal value logically. Finally, Objects.equals () tests for any nulls in the two strings then determine whether to call .equals ().
Ideal operator to use
Well this has been subject to lots of debates because each of the three operators have their unique set of strengths and weaknesses. Example, == is often a preferred option when comparing object reference, but there are cases where it may seem to compare string values as well.
However, what you get is a falls value because Java creates an illusion that you are comparing values but in the real sense you are not. Consider the two cases below:
Case 1:
Case 2:
So, it’s way better to use each operator when testing the specific attribute it’s designed for. But in almost all cases, Objects.equals () is a more universal operator thus experience web developers opt for it.
Here you can get more details: http://fluentthemes.com/use-compare-strings-java/
In addition to previous answers, you should be aware that there are strange behaviours associated with
-0.0f
and+0.0f
(they are==
but notequals
) andFloat.NaN
(it isequals
but not==
) (hope I've got that right - argh, don't do it!).Edit: Let's check!
Welcome to IEEE/754.
You can use Float.floatToIntBits().