• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Doubt regarding using same Object Memory for some case

 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have read in the K&B book that:

bytes, shorts, ints, booleans & chars exhibit immutability upto this range :
Boolean
Byte
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127

I have some doubt regarding same:
Integer i1 = 10;
Integer i2 = 10;
Integer i3 = new Integer(10);
Integer i4 = new Integer(10);

System.out.println("i1 == i2: " + (i1== i2) + " i3 == i4: " + (i3== i4));

It gives the o/p as: i1 == i2: true i3 == i4: false

Is it like that while creating the new Object using new keyword, the above mentioned rule is not applies.

Please help me to understand this issue.

Thanks in Advance.
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Anytime you use the keyword new, you are creating a new object. With autoboxing, certain references will refer to an already existing object.
 
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Integer i1 = 10;
Integer i2 = 10;
Integer i3 = new Integer(10);
Integer i4 = new Integer(10);
System.out.println("i1 == i2: " + (i1== i2) + " i3 == i4: " + (i3== i4));


Till 127 Java will cache the values and hence i1 and i2 will refere to same single Integer(10) object in heap. But when you do i3 = new Integer(10) you are telling the compiler to create a new integer object.
And hence in the above code i1 == i3 you get false instead of getting true.

Only during autoboxing as with i1 and i2 java will cache the values and make the references to point to same immutable 10 value.
Thanks
Deepak
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic