I would highly recommend that you read my previous post about String immutability in order to understand String immutability. This will help you to understand when and where to use String, StringBuffer or StringBuilder.
As explained in my previous post, String objects are immutable i.e. once an object is created with some value, its value can never be changed. If any manipulation is done to that string, a whole new String object is created while the old one remains in the memory. This may result in wastage of precious memory. So, if large number of operations are done on a string, a large number of objects will be created in memory(one object per operation). Those String objects will be of no use and will result in wastage of memory, which is a very precious resource.
It is where the StringBuffer and StringBuilder come into play. Any number of operations can be performed on a single StringBuffer or StringBuilder object. The changes will be reflected in that single object only unlike a String object in which a new String object is created for every operation performed on a string.
As explained in my previous post, String objects are immutable i.e. once an object is created with some value, its value can never be changed. If any manipulation is done to that string, a whole new String object is created while the old one remains in the memory. This may result in wastage of precious memory. So, if large number of operations are done on a string, a large number of objects will be created in memory(one object per operation). Those String objects will be of no use and will result in wastage of memory, which is a very precious resource.
It is where the StringBuffer and StringBuilder come into play. Any number of operations can be performed on a single StringBuffer or StringBuilder object. The changes will be reflected in that single object only unlike a String object in which a new String object is created for every operation performed on a string.
- String name="xyz";
- name.toUpperCase();
The new String object is created and instantly lost as no reference variable is referencing to it.(Wastage of memory) - name=name.toUpperCase();
The old string object "xyz" is lost now as the reference variable 'name' is now referencing to new String object.(Wastage of memory)






