Win a copy of Event Streams in Action this week in the Java in General forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

AutoBoxing and AutounBoxing

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer p=100;
Integer q=100;

System.out.println(p==q); output= true

And

Integer p=1000;
Integer q=1000;

System.out.println(p==q); output= false

i just add one 0 in second case then why false ?, how this happening?
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you create and Integer with static methods valueOf(), parseInt() or autoboxing, values in byte range (-128 to 127) will be reused, so == will return you true in these cases
 
Rancher
Posts: 128
7
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you create an Integer that is within -128 and 127 (and you do not use the new() keyword), it is stored in a cache.

 
Marshal
Posts: 65062
247
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Depending on the configuration of your runtime, you may find the same behaviour with a larger range of Integer objects, including (Integer)1000. See the documentation for Integer#valueOf(int) and the Java® Language Specification (=JLS). Integer is not strictly a value class, but it has quite a lot in common with value classes. It is a bad idea to use the == operator on reference types anyway, and as the 3rd link tells you, == can give you misleading results on value classes' instances.

That JLS section wrote:. . . the rule disallows any assumptions about the identity of the boxed values on the programmer's part.

The only place where == might be permissible is in a cert exam. Otherwise it is poor coding.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!