Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.4k points)

Given the 2 toString() implementations below, which one is preferred:

public String toString(){ return "{a:"+ a + ", b:" + b + ", c: " + c +"}"; }

or

public String toString(){ StringBuilder sb = new StringBuilder(100);

return sb.append("{a:").append(a) .append(", b:").append(b) .append

(", c:").append(c) .append("}") .toString(); }

?

More importantly, given we have only 3 properties it might not make a difference, but at what point would you switch from +concat to StringBuilder?

1 Answer

0 votes
by (46k points)

Method 1 is preferred because it's shorter and also, the compiler automatically converts it to method 2. And there's no performance difference between them.

When compiler can't substitute stringBuilder by itself than it switches from + concat. 

To read more about it click here.

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...