Search code examples
javaequalsequalityprimitiveautoboxing

How to ensure == will always work with primitives as an equality test


From what I understand, if I have two long or int, the == operator to test equality of values will not work sometimes due to autoboxing.

What do I need to do to ensure that == will work in every possible scenario when dealing with primitives?


Solution

  • Backward compatibility demands (and the JLS agrees) that if you had an expression like

    double a = ..
    double b = ...
    if (a == b) // condition
    

    This condition must work the same way it did before auto-boxing as after autoboxing. This means autoboxing cannot and must not apply here.

    In fact autoboxing is never used to compile an == expression if it can use unboxing instead.

    Integer i = 1000;
    int j = 1000;
    System.out.println(i == j); // is true
    

    In this case unboxing is chosen over boxing.