What's wrong with using == to compare floats in Java?

后端 未结 21 1957
你的背包
你的背包 2020-11-22 01:00

According to this java.sun page == is the equality comparison operator for floating point numbers in Java.

However, when I type this code:



        
21条回答
  •  旧时难觅i
    2020-11-22 01:20

    In one line answer I can say, you should use:

    Float.floatToIntBits(sectionID) == Float.floatToIntBits(currentSectionID)
    

    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:

    String a="Test";
    String b="Test";
    if(a==b) ===> true
    

    Case 2:

    String nullString1 = null;
    String nullString2 = null;
    //evaluates to true
    nullString1 == nullString2;
    //throws an exception
    nullString1.equals(nullString2);
    

    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/

提交回复
热议问题