hi String class has got final class and private variables so it's state is not changed In the sam way Stringbuffer has also got finla class and private variables but it is not called as immutable class ,why?
can any one please justiy
A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
I'm not sure if you're asking why String was made immutable and StringBuffer was not, or why String is said to be immutable, while StringBuffer is not. If it's the first, then you don't know what StringBuffer is for; in the latter case, it's that you don't know what "immutable" means. Based on history, I'm going to go with the second alternative.
"Immutable" just means "not changeable". Go look at every single method of String, and you won't find a single one that observably changes the state of the object it's called on. The "value" of a String never changes once a String object is created. As Jeremy says, there are lots of reasons why Strings guaranteed to never change are useful.
On the other hand, there are many methods that change the state of a StringBuffer: all the append() methods, setLength(), delete(), the insertXXX() methods, etc, etc. Changing the contents is the whole point of StringBuffer -- an immutable StringBuffer class would be useless!
I think of the immutability of Strings with regards to how String data is stored in memory.
String s1 = new String("ExamScam");
s1 points to a memory location containing the string ExamScam. If someone changes the string:
s1 = examscam.com;
Then a whole new memory location is used, and s1 is pointing at a completely new memory location. You can't adjust or fiddle with the memory location where a String stores its character data. You can with just about every other object class in Java.
That's sorta how I think about the immutability of the class. Certainly the term 'immutable' with regards to Strings goes beyond the simple fact that they can't be extended due to the use of the keyword final.
Originally posted by saikrishna cinux: hi String class has got final class and private variables so it's state is not changed In the sam way Stringbuffer has also got finla class and private variables but it is not called as immutable class ,why?
can any one please justiy
Actaully String class is using the FLYWEIGHT pattern inside. With the usage of the pattern one can accomadate more objects with same data. Let me put in this way, for example assume 100 people are accessing a application, in that first person created a string hello, and if other 99 people are also trying to create the work hello, there will be only one word hello in the pool and all the references will be pointed to it.
So it is not good to change this as every one is pointing to this one. Thats why strings are made immutable.