Reputation: 19857
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 + "";
Upvotes: 1
Views: 109
Reputation: 20073
The first is more commonly used for String Builder as @Peter Lawrey mentioned. However when casting to a String, it can be better to do...
(String) myVariable;
rather than...
myVariable.toString();
The reason for this is it's possible the second may throw a null pointer exception.
Upvotes: 1
Reputation: 533880
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.
Upvotes: 7
Reputation: 29730
There is a third possibility:
Objects.toString(Object o, String nullDefault)
the second argument is returned if the first is null
,
otherwise o.toString()
is returned.
(There is also Objects.toString(Object o)
, which returns the same as String.valueOf
)
Upvotes: 1
Reputation: 328923
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.
Upvotes: 5