This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using == on boxing/unboxing operations

 
Ravinder Singh
Ranch Hand
Posts: 54
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear ranchers,

The following code compiles and prints true.



In the above code, == is used to compare the bit pattern/values of an Integer object with an int primitive. It looked like from the result that Integer object is unboxed and then both the primitives values' are checked for equality thereby resulting in value true.

Q. Why is an Integer object being unboxed as opposed to primitive being boxed instead (in which case the result would have been false)?

Regards
Ravinder Singh
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Everything is driven by the Java Language Specification:
15.21.1 Numerical Equality Operators == and !=
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).


So the Integer object is unboxed to an int and a binary comparison takes place on the two operands. In comparing two entities representing numeric values, the most logical thing (to me) is to compare their values not their arbitrary memory addresses. Unboxing the Integer to an int is more optimal performance wise, than boxing the int and then comparing the numerical values of two Integer objects (which would anyway be a binary comparison).
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic