String is a final class hence cannot be extended by any class.
Any class which cannot be extended can also be called as immutable class.
StringBuffer is a class which can be extended (mutable).
Every time a new string is appended/added/removed to a string object, it creates a new string object and added to the existing string object.
1 2 |
String str = new String("testone"); str = str + "testtwo"; |
When a new String object is appended to StringBuffer object, it adds to the same memory of the existing String object already allocated., hence avoiding creating string objects every time..
1 2 3 |
StringBuffer strBufObject = new StringBuffer(); strBufObject.append("testone"); strBufObject.append("testtwo"); |
Hence appending or modifying string data or values using StringBuffer saves more memory.
It reduces overhead of new string objects created every time.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class StringExample { public static void main(String[] args) { String str = new String("testone"); str = str + "testtwo"; System.out.println("Ineffective String appending using string Class"); System.out.println(str); StringBuffer strBuf = new StringBuffer(); strBuf.append("testone"); strBuf.append("testtwo"); System.out.println("Effective String appending using StringBuffer Class"); System.out.println(strBuf.toString()); } } |
Result:
1 2 3 4 |
Ineffective String appending using string Class testonetesttwo Effective String appending using StringBuffer Class testonetesttwo |