The main difference between String and StringBuffer is that the former is immutable, while the latter is mutable.
By immutable, i mean that the value stored in the String object cannot be modified. Whereas, we can modify the values in StringBuffer.
For example,
Case 1:
String str = new String("This is first ");
str.concat("String");
System.out.println(str); //Ans : This is first
Case 2:
str = str.concat("String");
System.out.println(str); //Ans : This is first String
In the first case, the value is not appended, since the string is immutable. In the second case, we assigning the appended value to the object.
From this it is obvious that String is immutable.
By immutable, i mean that the value stored in the String object cannot be modified. Whereas, we can modify the values in StringBuffer.
For example,
Case 1:
String str = new String("This is first ");
str.concat("String");
System.out.println(str); //Ans : This is first
Case 2:
str = str.concat("String");
System.out.println(str); //Ans : This is first String
In the first case, the value is not appended, since the string is immutable. In the second case, we assigning the appended value to the object.
From this it is obvious that String is immutable.