Mark Harrison
Mark Harrison

Reputation: 304444

Java: toString vs. string concatentation?

Is there a reason to prefer either string concatenation or invoking toString when converting objects to string representations?

Does string concatenation cause the object's toString method to be invoked?

String s;
Properties p = System.getProperties();
s = p.toString();
s = "" + p;

Upvotes: 0

Views: 2185

Answers (1)

Matt Timmermans
Matt Timmermans

Reputation: 59174

p.toString() is better.

When you say s=""+p, the compiler makes something like this:

{
    StringBuilder sb = new StringBuilder();
    sb.append("").append(p.toString());
    s=sb.toString();
}

So, yes, ""+p does mean that p.toString() gets called, but it also adds a lot of extra work.

The best thing that can happen is that the compiler recognizes that it's the same as p.toString() and just calls that instead, but you shouldn't count on that.

Upvotes: 2

Related Questions