1

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 + "";
2
  • first one as second one creates extra StringBuilder object Commented Jan 7, 2013 at 15:23
  • @SuKu Hmm, are you sure? In my opinion the first will create only a String object, take a look at the implementation. The second, I agree, it will create an extra StringBuilder. Commented Jan 7, 2013 at 16:04

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain why is it more efficient? Is it linked with SuKu's comment to my question?
Wow, really ugly code. Now it's clear what is better. Thank you.
5

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.

2 Comments

I prefer getting an exception signalling the problem early, and allow me to fix the bug, as having null instead of the actual wanted result.
@JBNizet completely agreed. Rephrased.
1

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)

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.