I use toString() method. But I don’t know which implemention is better to use and why:
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("Description: " + description + ";");
buffer.append("Price: " + price);
return buffer.toString();
}
public String toString() {
return "Description: " + description + ";" + "Price: " + price;
}
Personally I’d use the latter – it’s clearer and is actually more efficient:
StringBuildertype instead ofStringBuffer"Price: " + priceand"Description: " + description + ";"which are unnecessary,Under Java 5+ I’d expect the latter code to be compiled to:
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: