String in a class it is used to holding the array of characters. The difference between String and StringBuffer is String is immutable where as StringBuffer is mutable. Means we can not change the value of the string.
Why it so?
Actually in java, Strings are handling in Pool format.
For example:
String str1 = “xyz”;
This string(str1) will be stored into memory in particular address. When we defining new String with same array of characters like
String str2 = “xyz”;
Now JVM will check in String Pool where there is same characters are available or not. If two Strings are match the JVM will refer str1 address to str2. Now the str1 and str2 referring the same characters in same memory location. This is a good idea for increasing memory efficiency.
When we change the str1 characters, the changes will be reflected to str2. Because both str1 and str2 variables are referring the same memory location. For avoiding this we are keeping String as immutable. However we can use StringBuffer if you want to do modifications in the string.
Hi ,
very nice answer.
Thanks
-Phanib
Very nice explanation
Thanks
very nice and usefull answer
Thanks
Very useful information. Thanks.
ThanQ Buddy……………Good Answer
Most importantly……..very Good Explanation
This is true only for string “xyz” (Literals) and not for new String(“xyz”) objects….
See here , I have compiled more reason for String immutability.
http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html
by the way nice to get some more good reason for string immutability.
hi , nice example..yar……
good answer I think …………
Great answer, thank u
just simple and nice answer
please give example .how the str1 character change. and it reflect in str2?
Excellent job..
Hi
I really thanks to u. nice answer
Very impressive answer dude and Useful also..
But explain with example are Give Clearly idea about It. …so dude exaplain with example….
Thanks nice answer…if anybody wants to know the interview questions with answers then please go through this blog http://adnjavainterview.blogspot.in/2014/06/why-string-is-immutable-or-final-in-java.html