2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Best approach for concatenation using StringBuilder or String in java

I am little confused between two classes StringBuilder and String that Java provides.

e.g

StringBuilder

public String getString(){
    StringBuilder sb = new StringBuilder(100);
    return sb.append("{a:").append(a)
          .append(", b:").append(b)
          .append(", c:").append(c)
          .append("}")
          .toString();
}

String

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

In both the cases method will return the same result.So now question is which one is preferable to use in coding?

userimage

Yes your confusion is acceptable and to make to little bit clarity on this here is my some explanation please note down so that you can find the best preferable approach on your posted question.

Generally we can switch to StringBuilder when it effects memory or performance.If you're really only doing this for a couple strings once, no worries. But if you're going to be doing it over and over again, you should see a measurable difference when using StringBuilder.

StringBuilder is a significant performance increase when working large strings just like using the + operator is a large decrease in performance (exponentially large decrease as the String size increases). The one problem with using .concat() is that it can throw NullPointerExceptions.

And the key point is whether you are writing a single concatenation all in one place or accumulating it over time (Means iteration).

Answer is