== operator return false if compare Double type with the same value

This question already has an answer here:

  • What's the difference between “.equals” and “==”? [duplicate] 11 answers

  • You are comparing references and not values. Either do:

    value1.equals(value2);

    or do:

    value1.doubleValue() == value2.doubleValue();

    Read more about Autoboxing here to figure out why this works sometimes (with integers) and why sometimes it does not. Notice that all integers are a summation of a power of 2: 6 = 2 + 4, whereas decimals are not: 6.2 = 4 + 2 + 1/8 + ...


    Both variables are initialized by a boxing conversion to a Double object. When using == on objects, the references are compared if they are the same object, and the contents are not compared.

    To compare the contents, you can use either the equals method, or you can check if the result of calling compareTo is equal to 0 . Or, you can declare both variables as double , and then == will compare the values directly.


    == Meant for reference comparison

    .equals Meant for content comparison

    1.In your code two objects will be created with references value1 and value2 pointing to different object.If you use value1==value2 it will return false .If references points to same object it will return true

    Double value1 = 6.2;
    Double value2 = 6.2;   
    

    2.If you use value1.equals(value2) it will compare the content of the objects which will return true

    链接地址: http://www.djcxy.com/p/58638.html

    上一篇: 从证书颁发机构申请证书

    下一篇: ==运算符如果比较具有相同值的Double类型,则返回false