String is immutable - Cannot be changed after creation
StringBuilder is mutable - Can be changed after creation hence suitable forappend, insertion and other modification operations. This class is unsynchronized which is it's advantage over StringBuffer.
Use StringBuilder when the string is going to be manipulated and at most only one thread will be accessing it.
Normally, when dealing with text, you should use String. There are good reasons why it is immutable - for example, this makes it much easier to make concurrent programs and makes optimizations such as string pooling possible.
Use StringBuilder when you need to build up text, for example by repeatedly appending things. Have a look at this example:
This code is very inefficient, because of the repeated String concatenations in the loop. For each iteration, a new String object will be made, for which the content of 'result' until that point will have to be copied. So this is what happens:
i = 1: result = new String object containing "A, B"
i = 2: result = new String object, first "A, B" is copied into it and then ", C" is appended
i = 3: result = new String object, first "A, B, C" is copied into it and then ", D" is appended
i = 4: result = new String object, first "A, B, C, D" is copied into it and then ", E" is appended
i = 5: ...
You see that every time the result until now is copied into a new String object - that's very inefficient. You can avoid this by using StringBuilder:
StringBuilder is mutable, it only needs to append ", " and names[i] in each iteration and it doesn't need to copy the whole result each time - so it's much more efficient.
My question still remain unanswered. Is there any real time situation whether we should recommend using String class and + operator for concatenation in place of StringBuilder .
This question seems to imply that the String and StringBuilder types are interchangable. They are clearly not.
If you are going to do a lot of string processing (creating of strings), then StringBuilder is probably a better candidate over Strings. The obvious exception is probably regular expressions, as the regex engine is better tied to Strings than the StringBuilder class. Regardless, even when you use the "+" operator on strings, the Java compiler will translate it to use string builders for you, so it is not that "inefficient".
However, if your methods are going to take parameters, it should be strings -- since you probably don't want to be passed something that can change (by another thread) while you are processing it. If you are going to return values, it should be strings -- or at least, a COPY of your string builders, as you don't want them to be mutated by the caller to your method.
It is this exact second reason that most of the builtin API takes strings, and not stringbuilders -- particulary the API that needs the security manager. It is impossible to check the validity of a request, if the request can change.