File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why String class is immutable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why String class is immutable" Watch "Why String class is immutable" New topic
Author

Why String class is immutable

yashprit singh
Greenhorn

Joined: Jan 04, 2011
Posts: 5

hello friends
i am new to this world so if this is very basic question then forgive me but i want proper explanation
i have two question

1.why string is immutable and why all wrapper class are immutable i know these are valued object but i don't get this
2.what is difference between String and StringBuilder class.
somewhere i read that immutable class are thread safe is this true??

thank you
Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 281



Hi Yashprit,

Exact answer of Why String class is immutable can only be provided by designer of java but here I see few reason which enforces immutability of String.


1)Imagine String Pool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file by passing name of file as argument to File I/O classes.

In one of my blog post I have discussed this you can check there for more details.
http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html


Now Why Wrapper classes are immutable, again there could be many different reason but immutability makes them pretty useful in multithreaded environment without worrying of thread safety issue also immutability makes them good candidate of being key in Hashtable and Hashmap .

Now to your third question
what is difference between String and StringBuilder class.
StringBuilder class has been added in Java 5 and provided similar functionality of StringBuffer (ie.. mutable string ) where on every modification on string , no new object gets created now benefit of using StringBuilder is that its comparatively faster than StringBuffer because StringBuffer is a synchronized class while StringBuilder is not , so in case if you want to use StringBuffer in a environment where thread safety is not concern , consider using StringBuilder for better performance.

Thanks
Javin


http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
yashprit singh
Greenhorn

Joined: Jan 04, 2011
Posts: 5

hey thank you Javin Paul

you have mentioned that immutable class like wrapper class useful in multithreaded environment without worrying of thread safety. then is this applied to String class??
are wrapper class and String class thread safe and if not then what do you mean by saying useful in multi-threaded environment

rest i like the explanation of String immutable answer pretty much stratified

thank you again
Sunny Bhandari
Ranch Hand

Joined: Dec 06, 2010
Posts: 448

He meant that Strings are so widely used in every program so if a String has been initialized then you don't need to worry about other threads modifying the value of String object.

Imagine a program where you are putting synchronized blocks just to make sure that other threads don't interfere with the string object you just created.

Is that clear now?


Java Experience
Prashant Shiralkar
Greenhorn

Joined: Apr 13, 2010
Posts: 19
why string is immutable and why all wrapper class are immutable i know these are valued object but i don't get this

By default, all Java classes are mutable i.e contents of their instances can be modified. But there are few advantages that immutability offers (http://download.oracle.com/javase/tutorial/essential/concurrency/immutable.html), and that's why some classes are made immutable by marking them as final. The classes in question are String and Wrapper classes, and if you think logically about them (any immutable class), then the description in the link provided would start making sense. Let us address each of the two separately:

String class:
As mentioned in SCJP page 433 by Kathy Siera and Bert Bates, as applications grow, its very common to have a lot of redundancy in the String literals for a program. Hence, in order to address this issue, the designers of Java came up with the concept of String pool which improves performance by making efficient use of available memory. But now, as you might imagine, if several reference variables refer to the same String without even knowing it, it would be bad if any of them could change the String's value. Hence, there arose the need of making this String class immutable.

Wrapper classes:
One of the objectives of making wrapper classes is to provide a mechanism to treat primitives with activities reserved for objects, like being added to Collections, or returned from a method with an object return value. If you think about a collection, it would often be the case that it is accessed by multiple threads. If the wrapper classes weren't mutable, it would run into the risk of concurrent modification and thus lead to inconsistent states. Thus, in order to avoid conflicts, wrapper classes are made immutable.

So, in general, whenever you come across an immutable class, it would be logical to think of its instances being used in a concurrent manner. Also, if you do not want your object contents to be modified (one of the reasons being concurrent access), then make the class immutable.
Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 281



Hi Yashprit,


you have mentioned that immutable class like wrapper class useful in multithreaded environment without worrying of thread safety. then is this applied to String class??
are wrapper class and String class thread safe and if not then what do you mean by saying useful in multi-threaded environment


Thread Safe class/object means we can safely use that object in a multithreaded environment without worrying about inconsistent object state due to multiple thread working on that. if a class is immutable means you can not change its state once it has been created so only read operation is possible on that , since no thread is writing or modifying its state , it can be safely shared between multiple thread without worrying about inconsistent object state.

Its recommended to make your object immutable as much possible to avoid any object inconsistency issue in multithreaded environment.

Since String and wrapper classes are immutable no once can modify object after creation so you can safely shared that between thread without worrying about object state.

hope this makes things clear.

Thanks
Javin
Shemida Nivedha
Greenhorn

Joined: May 22, 2008
Posts: 18
Hi Yashprit,

I found a link in JAVA RANCH which clearly states the String's immutable behaviour and how it could be made mutable.
Please go through the link - http://www.javaranch.com/journal/2003/04/immutable.htm

Thanks,
Shemida
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Why String class is immutable
 
Similar Threads
why string
On String
why Strings are immutable
Why was the String class made Immutable?
Strign.replace() replaceAll()