String is immutable. When you concat another string, it is created new object instead of manipulating the same string object. That's why is expensive when appending more string objects using +=.
Naresh Chaurasia wrote:If i try str = str1 + str2, then how many objects get created.
I believe ....
str = str1 + str2;
is converted to something like this ....
str = new StringBuilder().append(str1).append(str2).toString();
Looks like you are right. Quote from the API:
The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.
So, if you use the '+' sign in any case a new StirngBuilder or StringBuffer object will be created.