File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "strings " Watch "strings " New topic


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";
} o/p - abccdf;

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

Joined: Aug 26, 2005
Posts: 824
Check This

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 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.


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 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:
subject: strings
jQuery in Action, 3rd edition