Understanding Double autoboxing

Viewed 1948

Consider the following example:

public static void main(String[] args) {
    double x1 = 0.0, y1 = -0.0;
    Double a1 = x1, b1 = y1;
    System.out.println(x1 == y1);       //1, true
    System.out.println(a1.equals(b1));  //2, false

    double x2 = 0.0, y2 = 0.0;
    Double a2 = x2, b2 = y2;
    System.out.println(x2 == y2);       //3, true
    System.out.println(a2.equals(b2));  //4, true

    double x3 = 0.0/0.0, y3 = 0.0/0.0;
    Double a3 = x3, b3 = y3;
    System.out.println(x3 != y3);       //5, true
    System.out.println(!a3.equals(b3)); //6, false
}

I tried to understand the autoboxing for Double, but could not. Why does the //2 print false, but //4 prints true whereas both //1 and //3 prints true. Why are they autoboxed in a different way?

Consulting the following JLS 5.1.7 section I realized that it's not specicified:

If p is a value of type double, then:

  • If p is not NaN, boxing conversion converts p into a reference r of class and type Double, such that r.doubleValue() evaluates to p

  • Otherwise, boxing conversion converts p into a reference r of class and type Double such that r.isNaN() evaluates to true

So, are //2, //4 and //6 yeild in unspecified behavior and might end up in different results depending on the implementation?

5 Answers
Related