Two Laptop Bag*
The moose likes Java in General and the fly likes Why is the String Class Immutable? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why is the String Class Immutable?" Watch "Why is the String Class Immutable?" New topic
Author

Why is the String Class Immutable?

nitin pai
Ranch Hand

Joined: May 30, 2006
Posts: 185
Why is String implemented as a immutable class. If you however want an object in which the text can be manipulated you use the StringBuilder class. Then what was the exact purpose to make String class immutable. We could have used it directly in place of StringBuilder. Isnt it?



Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265

There are dozens if not hundreds of discussions on the web about why Java Strings are immutable. It is actually interesting to read the many threads, and I would highly encourage everybody to do so as a way to learn more about the language.

One interesting topic to pursue is that javac itself is written in java, and why that may have impacted the decision to make Strings immutable in Java.

The point is that we're not limited in Java by the immutable nature of Strings; we have StringBuilder and StringBuffer to give us better performance for cases where we need to manipulate Strings.


There will always be people who are ahead of the curve, and people who are behind the curve. But knowledge moves the curve. --Bill James
Nicholas Jordan
Ranch Hand

Joined: Sep 17, 2006
Posts: 1282
Yes, it is like Steve says. Originally there was an issue several languages back, that is followed by preventing the un-intended changing of variables. That would happen because there are so many variables. Then, when the String class was final - I did not fall for it. Sorta conceptually weak but you can change a String to point to a new String. We get into a convoluted reverbaration discussing the matter. I now just read whatever some class is stated to do and take it at that. If worst comes to too bad, I just write a utility class at the end of the file that does what I want and skipp all the skippy peanuts.
nitin pai
Ranch Hand

Joined: May 30, 2006
Posts: 185
Ok I can understand that this issue has been prevailing from ages. But when a new API is released cant it be changed to become mutable. My question was why it is still the same way even when Java has upgraded its collections framework with Generics.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Nitin --

One important reason was that the JVM is designed to enable secure "sandbox" operation, meaning that unknown Java code -- like an applet downloaded from the Internet -- can be run safely. Immutable Strings help ensure that safety.

Here's a concrete example: part of that safety is ensuring that an Applet can contact the server it was downloaded from (to download images, data files, etc) and not other machines (so that once you've downloaded it to your browser behind a firewall, it can't connect to your company's internal database server and suck out all your financial records.) Imagine that Strings are mutable. A rogue applet might ask for a connection to "evilserver.com", passing that server name in a String object. The JVM could check that this server name was OK, and get ready to connect to it. The applet, in another thread, could now change the contents of that String object to "databaseserver.yourcompany.com" at just the right moment; the JVM would then return a connection to the database!

You can think of hundreds of scenarios just like that if Strings are mutable; if they're immutable, all the problems go away. Immutable Strings also result in a substantial performance improvement (no copying Strings, ever!) and memory savings (can reuse them whenever you want.)

So immutable Strings are a good thing.


[Jess in Action][AskingGoodQuestions]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[NP]: But when a new API is released cant it be changed to become mutable. My question was why it is still the same way even when Java has upgraded its collections framework with Generics.

I suppose in theory Sun could always come out a different API that changes previous behavior. This might well break some existing code however - for example if the code relies on the assumption that a String is immutable (as much code does). But in general, Sun is very, very reluctant to make changes like this that will break exiting code. There are many classes and methods that could be designed better than they were originally, but Sun will not change these because it's very important to keep existing code functioning correctly. Sun will often add new classes and methods, but they are very very reluctant to make other changes to behavior. This is true for many potential issues, not just immutability. The changes to Collections, and generics in general, were the biggest ever made to the language since it came out, and Sun limited these changes (perhaps unfortunately) to be sure that existing code would still function as before. So what I'm saying is, while it's always possible that Sun may change things drastically in the future, it's not generally something worth worrying about, I think. They are fairly conservative about changes.


"I'm not back." - Bill Harding, Twister
Stevi Deter
Ranch Hand

Joined: Mar 22, 2008
Posts: 265

The decision to make String immutable goes beyond just historial compiler issues, and the other contributors to this discussion have given great evidence as to why it's a good decision.

It's fairly standard in advanced programming languages to have immutable strings. For example, C# chose to use immutable strings and provide a StringBuilder class for cases where this behavior wasn't desired.
Guido Sautter
Ranch Hand

Joined: Dec 22, 2004
Posts: 142
An additional issue is that Java does not allow for overloading operators (as opposed to C/C++) for a series of reasons. There's only one exception to this: the + operator for concatenating Strings. If the String class provided methods for modification, or even was non-final, the special treatment of the + operator in combination with Strings might result in unpredictable behavior.

Yet another reason is that the actual content of String constants would become mutable if Strings were mutable, with unpredicatble impact on existing code, plus a great opportunity of causing havoc in JRE native classes that use String constants.
Mohammed Yousuff
Ranch Hand

Joined: Oct 17, 2007
Posts: 198
as i learned The main reason why string was not made as mutable, is due to the security issue in Java.. However in Applets if some thread can change the value of String object, why can't that thread can create new String object and do the same operations?....

Can any please give me some example code so that it will be more clear... thanks ;)


My Thoughts : http://passion4java.blogspot.com
Try not to become a man of success but rather to become a man of value.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18508
    
  40

Mohammed Yousuff wrote:as i learned The main reason why string was not made as mutable, is due to the security issue in Java.. However in Applets if some thread can change the value of String object, why can't that thread can create new String object and do the same operations?....

Can any please give me some example code so that it will be more clear... thanks ;)



Did you read EFH's example? And how does your change (create new string object and do "same operation") circumvent security?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 281


See here for some reason of string immutability


http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html


http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3575
    
  14

Not just Strings. Working with immutable classes greatly reduces overall complexity. Immutable classes are inherently thread-safe, they are more secure as mentioned earlier, you don't need to make defensive copies of them, and they are just easier to work with in general. I always strive to make as many classes immutable as I can.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why is the String Class Immutable?
 
Similar Threads
how can we assign a text in front text.
Why String class is immutable
Difference of equals method in string and stringbuffer
String's insert
Strign.replace() replaceAll()