JVCHBABU
JVCHBABU

Reputation: 21

Double.NaN is an object

public class Double1 {    

    public static double parseDouble(String _s, double _def) {
        try {
            return Double.parseDouble(_s);
        }
        catch(Exception e) {
        }
        return _def;
    }

    public static void main(String[] args) {
        Double1 db=new Double1();
        boolean ab=db.parseDouble("vijay", Double.NaN)!=Double.NaN?true:false;
        System.out.println("ab value: "+ ab);
        System.out.println(Double.NaN==Double.NaN);
    }
}

It should return true where as the above code returns false. Why?

Upvotes: 1

Views: 816

Answers (2)

Voo
Voo

Reputation: 30216

NaN's compare false to everything - including themselves.

You can check for NaN with

Double.isNaN(doubleValue)

Which actually does nothing other than using exactly this behavior: A value x is a NaN if x != x.

Upvotes: 14

shift66
shift66

Reputation: 11958

but it's normal. Your parseDouble method tries to parse "vijay" and returns _def because "vijay" is not a double value.And db.parseDouble("vijay", Double.NaN) will return Double.NaN an finally Double.NaN!=Double.NaN is false.

Upvotes: 0

Related Questions