In Java, does "==" Box or Unbox when comparing an object and a constant value?

Amrish Kumar :

When comparing an Integer object and a constant value, does Java box the value or unbox the Integer object?

Based on what I have read, "==" is a reference comparison, therefore it's only logical to assume that Java boxes the constant to perform the reference comparison between the objects. Yet, the below test code seems to be give contradictory results.

Integer v1 = 1000;
Integer v2 = 1000;
boolean b1 = v1 == 1000; //True.
boolean b2 = v1 == v2; //False. Proof that 1000 boxes to new object and is not fetched from cache.

So how does object vs constant value comparison using == works in Java? Does the operator compare by value in this case?

Eran :

What you call "a constant value" is an int literal, so its type is int.

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.

In your v1 == 1000 test, 1000 is of numeric type and v1 is convertible to numeric type, so binary numeric promotion is performed.

JLS 5.6.2 (Binary numeric promotion) says:

If any operand is of a reference type, it is subjected to unboxing conversion

Hence, the Integer operand - v1 - is unboxed to an int and a comparison of two ints is performed. Therefore the result of the comparison is true.

When you compare two reference types - v1 == v2 - no unboxing takes places, only the references are compared, as written in JLS 15.21.3:

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

Since 1000 is too large to be cached by the Integer cache, b1 and b2 are not referencing the same instance, and therefore the result of the comparison is false.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23120&siteId=1