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.