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 | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
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: 41575
    
  31
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: 11688
    
  18

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Campbell Ritchie
Sheriff

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

Joined: Oct 13, 2005
Posts: 41575
    
  31
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: 41575
    
  31
Welcome to the Ranch
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: String classes