• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Boxing == Long

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Looks like two instances of Long,
1) created through autoboxing,
2) between -128 and 127,
compares their primitive values when using ==.

Boolean, Character(0 to 127) and Byte/Short/Integer(-128 to 127) following 1) and 2) are known to compares their primitive values when using ==, but is this also true for Long (-127 to 128)?

(Long is not listed in Sierra-Bates 5 page 236)
Regards,
Teo
[ October 16, 2007: Message edited by: Teo Framoe ]
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Teo Framoe:
...Boolean, Character(0 to 127) and Byte/Short/Integer(-128 to 127) following 1) and 2) are known to compares their primitive values when using ==, but is this also true for Long (-127 to 128)? ...


First, note that == applied to wrapper instances is a comparison of object references. It is not comparing the primitive value wrapped.

The optimization described in JLS - 5.1.7 Boxing Conversion results in equal primitive values within a certain range boxing to the same wrapper instance. So again, it's the references to these objects -- not the primitive values -- that are being compared by ==.

Now, according to 5.1.7...

If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
...

For other values, this formulation disallows any assumptions about the identity of the boxed values on the programmer's part. This would allow (but not require) sharing of some or all of these references.


So, as I understand it, this behavior is ambiguous when applied to long values.
 
I'm full of tinier men! And a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic