Which way of converting Java object to String would you recommend and why?
For example, assume we have:
StringBuilder sb = new StringBuilder();
We can convert it to String in two ways. First:
sb.toString();
Second:
sb + "";
The first is preferred as it is more commonly used and more efficient.
You would only use the second if the String were not empty (in which case you should append it to the StringBuilder)
The second example is more expensive because it is much the same as
new StringBuilder().append(sb.toString()).append("").toString();
Technically it does this.
new StringBuilder().append(String.valueOf(sb)).append("").toString();
the difference being that String.valueOf(null) => "null" instead of an NPE.
The main difference between someObject.toString() and someObject + "" is if someObject is null: the former will throw a NullPointerException whereas the latter won't (it will return "null").
If you expect your object to be non-null, then:
String s = someObject.toString();
saves an unnecessary concatenation (which might or might not be removed by the compiler).
However, if the object can be null and it is an acceptable value, I'd rather go for:
String.valueOf(someObject);
In this example, if someObject is null, it will return "null" and won't throw an exception.
StringBuilderobjectStringobject, take a look at the implementation. The second, I agree, it will create an extraStringBuilder.