Search code examples
javaobjectdoublecomparison

Double comparison failing in Java


Why does the first if-statement return true and the second false?

Isn't 100000000000000.032 in the first if-statement also turned into a new Double that is different to dd?

Double dd = 100000000000000.032;
if(dd == 100000000000000.032) {
    System.out.println("gaga");
}

Double ee = 100000000000000.032;
if(dd == ee) {
    System.out.println("gaga");
}

Solution

  • Either you follow Majed Badawi's answer to use equals() because you compare object instances, or you modify your code like below:

    double dd = 100000000000000.032
    if( dd == 100000000000000.032 ) 
    {
        System.out.println( "gaga" );
    }
    
    double ee = 100000000000000.032;
    if( dd == ee ) 
    {
        System.out.println( "gaga" );
    }
    

    Note that dd and ee are now of the primitive type double (with a lowercase 'D').

    In your sample, the first comparison worked because internally, it was interpreted as:

    … 
    if( dd.doubleValue() == 100000000000000.032 ) 
    …
    

    This behaviour is called 'Autoboxing/-unboxing' and was introduced with Java 5; for versions before Java 5, your code would not compile at all.