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?
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
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.
Please use [highlight=Java] code [/highlight] tags when posting your code.
Forum Tip: Add to peoples reputation by clicking the button on their useful posts.