Win a copy of AWS Security this week in the Cloud/Virtualization 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
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

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: 29
  • 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: 260
12
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: 69527
277
  • 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.
 
If you were a tree, what sort of tree would you be? This tiny ad is a poop beast.
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic