• 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

question regarding auto-box/unbox

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Integer a=1000,b=1000,c=10,d=10;
if(a!=b){System.out.println("Not")}
if(a==b){System.out.println("Yes");}
//It prints out "Not" and "Yes"
but why when i change a and b=100 it only show "Yes"

Someone please clarify ?
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Normally, when the primitive types are boxed into the wrapper types, the JVM allocates memory and creates a new object. But for some special cases, the JVM reuses the same object.

The following is the list of primitives stored as immutable objects in cached pool:

boolean values true and false
All byte values
short values between -128 and 127
int values between -128 and 127
char in the range \u0000 to \u007F
 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This example will print only Not
When i change a and b=100 it only show "Yes"

Integer class with value from -128 to 127 in Java pools

Integer i1 = -128;
Integer i2 = -128;
i1==i2 - true, because i1 and i2 from pool

Integer i1 = -129;
Integer i2 = -129;
i1==i2 - false

Integer i1 = 127;
Integer i2 = 127;
i1==i2 - true, because i1 and i2 from pool

Integer i1 = 128;
Integer i2 = 128;
i1==i2 - false


But

Integer i1 = new Integer(127);
Integer i2 = new Integer(127);
i1==i2 - false, because i1 and i2 create at Runtime, not from pool
 
WHAT is your favorite color? Blue, no yellow, ahhhhhhh! Tiny ad:
Free, earth friendly heat - from the CodeRanch trailboss
https://www.kickstarter.com/projects/paulwheaton/free-heat
reply
    Bookmark Topic Watch Topic
  • New Topic