Question

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?

Was it helpful?

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.

OTHER TIPS

The JLS (§15.21.1) says:

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

So the problem you describe occurs only if both operands are boxed types (Double, Integer, etc.). Whether the operand type is boxed or not depends on how the operand is declared. If it's a variable, field or parameter, it depends on the type used to declare the name; if it's a method call, it depends on the return type used when the method is declared; if it's the result of some other operation like +, it should already be unboxed; if a typecast has been applied, the cast will tell you what the type is.

As others have said, you usually shouldn't use == to compare doubles or floats due to rounding errors.

Fafaik you can not get boxing with two primitives. Boxing occurs when you were to take (for example) and int and an Integer, or a double and a Double. Unboxing get the primitive from the "box" (the Object equivalent) to then compare the two primitives with the == operator, in which case there is no guarantee they are the same. If you have two doubles however you will not have this problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top