Curds
Curds

Reputation: 181

Java - comparison of positive and negative zeros

Why is Java inconsistent in comparing -0.0 and +0.0? What is the Java standard method for comparing numbers to account for -0/+0?

I have encountered this particular bugaboo:

public class ZeroCompare {
    public static void main(String[] args) {
        if ( 0.0 == -0.0 ) {
            System.out.println("== --> same");
        } else {
            System.out.println("== --> different");
        }

        if ( new Double(0.0).equals( -0.0 ) ) {
            System.out.println("equals --> same");
        } else {
            System.out.println("equals --> different");
        }
    }
}

It prints the following:

== --> same
equals --> different

I strongly dislike the fact that how you compare these two values affects the outcome and I'd love for an explanation.

Upvotes: 9

Views: 2376

Answers (2)

sibnick
sibnick

Reputation: 4305

Java Language Specification: Numerical Comparison Operators <, <=, >, and >=

Positive zero and negative zero are considered equal.

Double.valueOf(+0.0) and Double.valueOf(-0.0) have different bits representation. Double.equals compares bit representation.

Also you can use Double.compare

Upvotes: 2

Tunaki
Tunaki

Reputation: 137229

This behaviour is actually documented:

If d1 represents +0.0 while d2 represents -0.0, or vice versa, the equal test has the value false, even though +0.0==-0.0 has the value true. This definition allows hash tables to operate properly.

Upvotes: 12

Related Questions