This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "strings " Watch "strings " New topic
Author

strings

harish shankarnarayan
Ranch Hand

Joined: Sep 12, 2005
Posts: 158
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;


Harish<br />SCJP 1.4 (85%)
Sunil Kumar Gupta
Ranch Hand

Joined: Aug 26, 2005
Posts: 824
Check This


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


It will help u to understand


Lack of will power has caused more failure than lack of intelligence or ability.
My Blog | Red5 Resources | Technology Update | Daily Technology Tips
Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
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


Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
anand phulwani
Ranch Hand

Joined: Sep 10, 2005
Posts: 242
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


Thanks and Regards, Anand
SCJP 5.0 310-055 73%, SCWCD 1.4 310-081 78%, IBM DB2 9 Fundamentals 000-730 62%
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: strings