• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Using == on boxing/unboxing operations

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
reply
    Bookmark Topic Watch Topic
  • New Topic