2

Possible Duplicate:
when to use StringBuilder in java

If not which of these pieces of code is better and why

public String backAround(String str) {
   int len = str.length();
   StringBuilder sb = new StringBuilder(str);
   char chEnd = sb.charAt(len-1);
  if(len > 0){
  sb = sb.append(chEnd);
  sb= sb.insert(0,chEnd);

  str= sb.toString();
  return str;

  }else{ return str;}
}

or

public String backAround(String str) {
  // Get the last char
  String back = str.substring(str.length()-1, str.length());
  return back + str + back;
}
Community
  • 1
  • 1
Dave
  • 4,184
  • 8
  • 40
  • 46

2 Answers2

6

If you are just "sticking a few elements together" as in your backAround() method, you may as well just use the + notation. The compiler will convert this into appropriate StringBuilder.append()s for you, so why bother 'spelling things out'.

The idea of explicitly using StringBuilder is that in principle you can hand-optimise how exactly the elements are appended to the string, including setting the initial buffer capacity and ensuring that you don't accidentally create intermediate String objects that are unnecessary in cases where the compiler might not predict these things.

So essentially, explicitly use a StringBuilder when there is slightly more complex logic to deciding what to append to the string. For example, if you are appending things in a loop, or where what is appended depends on various conditions at different points. Another case where you might use StringBuilder is if the string needs to be built up from various methods, for example: you can then pass the StringBuilder into the different methods and ask them to append the various elements.

P.S. I should say that StringBuilder buys you a little more editing power as well (e.g. among other things, you can set its length) and, given the presence of the Appendable interface, you can actually create more generic methods that either append to a StringBuilder or to e.g. a StringWriter. But these are marginal cases, I would submit.

Neil Coffey
  • 21,615
  • 7
  • 62
  • 83
1

It really depends on what you are trying to do. In your case it seems like your trying to take a string and take the last letter and add it to the front and then add another to the end. For this i would probably do this:

public String manipulate(String string)
{
    char c = string.charAt(string.length);
    return c + string + c;
}

In this case you didn't have to use a StringBuilder. There are cases where the StringBuilder class is useful. Here are some things that are hard to do with a String that StringBuilder can do:

  • delete chars at an index
  • append chars at an index
  • get the index of a specific sequence
  • and much much more

if you want to see the documentation for StringBuilder:

String Builder

I hope this helped you out!

John
  • 3,769
  • 6
  • 30
  • 49