Strings are immunable – What does this mean? When I change a String with a string operation like replace or StringBuffer then the changed String is a new string object / reference In this case s2 has the same content as s1 after a string Operation. But s2 is not pointing to the same reference (memory place) than s1 as s2==s3 is not true.
String s2 = s1.replace('m','r'); The line above s1.replace('m','r') return's a String object... it is same as creating String s2 = new String("amit"); When you give (s2==s3) the answer is false, because they r referring to different memory locations..
The word is "immutable" and it means the value can't be changed. That's why your example is showing so many references and why your "==" returns false. Joshua Bloch's book "Effective Java" devotes eight pages to the topic. He is convinced that most classes should be immutable, as String is. Reasons include: Immutable classes are thread-safe, can be shared freely, are simple, and make good building blocks for other classes. Down side is that they require a separate object for each value -- as you saw. That's why there is the Stringbuffer class, a mutable class.
Joined: Mar 08, 2001
Hello, could you please post a few examples or references to web sites where this is explained in detail? Thanks. Thomas
Originally Quoted by Norm Miller : Down side is that they require a separate object for each value -- as you saw. That's why there is the Stringbuffer class, a mutable class.
Oops do you mean that every val of string has one more object and that means more memory usage. If so how one can control the memory usage. consider this example: String retval = ""; retval = "Passed"; retval = "faled"; Do you mean for above code there will be three objects in memory and if so what is the solution except using String Buffer class? regards, arun
Joined: May 21, 2002
If you look at the thread Anthony refers to, it shows that all that object creating and destroying does, in fact, happen. You probably shouldn't worry about it too much if you aren't changing the String a lot, but use Stringbuffer if the situation calls for it -- it isn't that difficult. There is more info on the earlier thread ( started Sept 9 2002 by Joshua Austin). On that thread, Max Habibi makes the observation that the StringBuffer becomes a better choice at about 300 changes. On other boards, I have seen numbers ranging from about 5 to 50 before you invoke Stringbuffer. Has anybody tested this performance angle and published the result? [ September 12, 2002: Message edited by: Norm Miller ]