What is meant by 'string' and 'string buffer'
What are the differences.Please help me
What is use of Capacity method.How does it work?
Printable View
What is meant by 'string' and 'string buffer'
What are the differences.Please help me
What is use of Capacity method.How does it work?
In Java a String instance is immutable. This means that once created it cannot be changed. For example you cannot remove the trailing spaces at the end of this String: "abc ". If you do it by calling the trim() method a new String instance will be created containing only "abc". Immutability helps by controlling side effects and by avoiding hard to find bugs related to multi-threading. But there is a performance penalty to pay.
A StringBuffer is a mutable representation of a string. You can actually change the content of the StringBuffer instance. When you create a StringBuffer instance you have the option of specifying how big the buffer is initially, in number of characters. By default the internal buffer size is 16. The capacity() method tells you how many characters you can add to the buffer before it needs to allocates some more memory. This is done transparently so usually you don't care unless you think really hard about performance.
If you think really hard about performance you have to keep in mind that StringBuffer is synchronized - this means thread safe. this introduces by itself some performance issues.
Java API provides also the StringBuilder class. This class is compatible at the API level with StringBuffer but it is not synchronized. This means it is faster to use but safe only when no multiple threads try to access its instances at the same time.
Good answer danielstoner.
Welcome to the Java Programming Forums. :cool: