Personally I'd use the latter - it's clearer and is actually more efficient:
- For modern versions of Java it'll use the unsynchronized
StringBuilder
type instead of StringBuffer
- It won't construct the intermediate strings for
"Price: " + price
and "Description: " + description + ";"
which are unnecessary,
Under Java 5+ I'd expect the latter code to be compiled to:
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Description: ");
builder.append(description);
builder.append(";");
builder.append("Price");
builder.append(price);
return builder.toString();
}
The important point is the clarity of the second form, however - I certainly find it much simpler to read than the first. One interesting point is that there are two consecutive calls to append with string constants in the compiled version (I've checked). It would be slightly more efficient - and even more readable, IMO - to write:
public String toString() {
return "Description: " + description + ";Price: " + price;
}