What is the difference between the String and StringBuffer classes?
String class is immutable. The characters of string objects can not be changed / modified.
StringBuffer is mutable. The characters of StringBuffer objects can be modified / changed.
String class is used for simple investigations on string objects.
StringBuffer’s performance is faster than String when concatenating other strings. String class concatenates the other string by using + sign. After concatenation, it returns another String object. This string object can be reassigned to the original String reference.
Example :
str = str + “to India” ;// where str=”Welcome”
The concatenation creates a temporary String object and is reassigned to str.
Using StringBuffer, the concatenation is done by using append() method.
Example :
str.append(“to India”); // str is a StringBuffer object’s reference variable and //assigned “Welcome”.
The concatenation is done only by appending the “string to India” to the original StringBuffer object “Welcome”.