my dog learned polymorphism*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 38057
    
  22
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: 11169
    
  16

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: 38057
    
  22
niras iva,
Your post was moved to a new topic.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38057
    
  22
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: 38057
    
  22
Welcome to the Ranch
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: String classes
 
Similar Threads
regarding strings
Immutable classes
strings are immutable!!
regarding strings
Strings Immutable ??