Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why String class is immutable

 
yashprit singh
Greenhorn
Posts: 5
Java MySQL Database Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
yashprit singh
Greenhorn
Posts: 5
Java MySQL Database Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 448
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Prashant Shiralkar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic