Search code examples
javaautoboxing

How Java compares two wrapper variables?


I have two variables that should be compared:

Double a = 1D;
Double b = 2D;

if (a > b) {
    System.out.print("Ok");
}

In this case java will use autoboxing or compare two object's references?


Solution

  • From section 15.20.1 of the JLS:

    The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs. Binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then signed integer comparison is performed; if this promoted type is float or double, then floating-point comparison is performed.

    Section 5.6.2 starts with:

    When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

    • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed.

    So yes, unboxing is performed. > has no meaning for references themselves.

    More interesting is the == case where both options would be possible - and in that case, if either operand is a primitive and the other can be converted via numeric promotion, then that happens... but if both are reference types, the reference comparison is performed. For example:

    Double d1 = new Double(1.0);
    Double d2 = new Double(1.0);       
    System.out.println(d1 == d2); // Prints false due to reference comparison