StringBuffer
is a mutable class. The setString2()
method takes a StringBuffer
as argument, modifies it, and also returns it. The setString()
method takes a StringBuffer
as argument, modifies it, but doesn't return it.
Both programs do the same thing and produce the same result. The second solution is cleaner though: there is no reason to return something that is passed as argument. Indeed, the caller already has a reference to the object that it passes as argument, and returning this object is thus useless, and causes confusion: why does the method return a StringBuffer? Is this StringBuffer the same as the one passed as argument, or a new one? Is the StringBuffer passed as argument modified, or is the method returning a modified copy of it?
The second method doesn't have all these ambiguities.
Side note: You shouldn't use StringBuffer
anymore. Prefer StringBuilder
instead.