Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strings

 
harish shankarnarayan
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String class is immutable right ,
but the code below changes its value ,how?
can anyone explain string and string buffer class with respect to this reference with example,i.e wat exacltly mutable and immutable means.

it may be a trivial one,but i didnt get it
class test
{
public static void main(String [] args)
{
String a="abc";
a=a+"cdf";
System.out.println(a);
}
} o/p - abccdf;
 
Sunil Kumar Gupta
Ranch Hand
Posts: 824
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check This


http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html


It will help u to understand
 
Sandeep Chhabra
Ranch Hand
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi harish,
when you do
a=a+"cdf";
a new String Object is created containing "abccdf", and this new objects address is now assigned to a. This is because Strings ar immutable.

the object prior to concatenation still remains in the memory(until it is GC) and now a contains new object.

Hope this help you.

Sandy
 
anand phulwani
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Harish,

When you create a String Object it is immutable,You wont be able to modify the object,in your case you have changed the reference to the object,here you have created a new object and made your Object 'a' refer to it,while the old object still remains in the pool(until Garbage Collector collects it).

Correct Me If I Am Wrong.

Thanks,
Anand
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic