File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes String classes Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "String classes" Watch "String classes" New topic
Author

String classes

niras iva
Greenhorn

Joined: May 10, 2011
Posts: 18
String is immutable:

String s="hello";

s+="bfgkjdf";

Now the value of s is changed.. then how string is immutable?please explian it clearly
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32599
    
    4
You are creating a new String object"hellobfgkjdf" and substituting that for the original String. The two Strings "hello" and "bfgkjdf" still exist, but are unreachable because their references are changed.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 9939
    
    6

because s is not a string. it is a REFERENCE to a string. The String object "hello" still exists unchanged, but you no longer have a reference variable pointing to it.

It is similar to having an address card that points to a house. you can change the address written down on the card, but the original house is unchanged.


Never ascribe to malice that which can be adequately explained by stupidity.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32599
    
    4
niras iva,
Your post was moved to a new topic.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32599
    
    4
I earlier wrote:niras iva,
Your post was moved to a new topic.
That was because you added an unrelated question to an old thread.
John Hua
Greenhorn

Joined: Jun 05, 2011
Posts: 1
You should know the String class was defined as public final class String.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 32599
    
    4
Welcome to the Ranch
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: String classes
 
Similar Threads
Immutable classes
strings are immutable!!
regarding strings
Strings Immutable ??
regarding strings