This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
You cannot make StringBuffer immutable. In fact, you cannot make any class immutable without modifying the source code of the class - and since StringBuffer is a class in the standard Java library, you can't modify its source code.
You ought usually to use StringBuilder rather than StringBuffer.
Both classes are specially designed to be easily mutable. They are counterparts to the String class, which is designed to be immutable. So you ought not even to try making a mutable StringBuilder.
Rajdeep Biswas wrote:I think we have to modify the source code such that it prevents resetting the instance or changing the object state
As Campbell has already said, the whole point of the StringBuffer and StringBuilder classes is that they are mutable, if you want an immutable version then just use a String class.
Joined: Oct 13, 2005
Those classes were written as mutable classes because String is immutable. Anyway, you can’t alter the source code because the compiler won’t compile anything claiming to be in the java.lang package. And close examination of the documentation will reveal something else about StringBuilder.