2.1 Difference Between Java String and StringBuffer
The main difference between String and String Buffer is that String is immutable where as String Buffer is not immutable. In earlier chapter we discussed the immutable concept.
As any change in immutable object returns a new object which means there will be many objects.
It is always advisable to use StringBuffer in a loop as using String will create several objects.
Let’s assume we have a requirement to create a String of n numbers like 1234....n. We can do this by running a loop and concat String OR by using StringBuffer.
2.2 Example using String and String Buffer
Below code implements two methods using String and StringBuffer. In such scenario, always use StringBuffer as only one object will be created where as in String approach , there will be 100 object created as String is immutable.
public class Test { public static void main(String[] args) { useString(); useStringBuffer(); } private static String useString() { String s = ""; for(int i=1;i<100;i++) { s=s+i; } return s; } private static String useStringBuffer() { StringBuffer sb = new StringBuffer(); for(int i=1;i<100;i++) { sb.append(i); } return sb.toString(); } }