wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Using == on boxing/unboxing operations Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Using == on boxing/unboxing operations" Watch "Using == on boxing/unboxing operations" New topic
Author

Using == on boxing/unboxing operations

Ravinder Singh
Ranch Hand

Joined: Mar 06, 2006
Posts: 54
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

Joined: Aug 03, 2002
Posts: 7729
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).


Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
wood burning stoves
 
subject: Using == on boxing/unboxing operations