Help me understand the java stringbuffer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • anthonette50
    New Member
    • Mar 2008
    • 2

    Help me understand the java stringbuffer

    I am trying to understand what the code below is doing, i know the functions of a string buffer, however am finding it difficult to interprete the aim of the code below. Hope someone can help me?

    public string tostring(){
    stringBuffer sb=new StringBuffer(28 );
    sb.append("move [x: ");
    sb.append(x);
    sb.append("; y: ");
    sb.append(y);
    sb.append(";val : ");
    sb.append(getVa l());
    sb.append("] ");
    return sb.string();
    }
  • BigDaddyLH
    Recognized Expert Top Contributor
    • Dec 2007
    • 1216

    #2
    The code is doing the same as:

    [CODE=Java]return "move [x: " + x + "; y: " + y + "; val: " + getVal() + "]";[/CODE]

    I don't see the advantage to using a StringBuffer in this case.

    Comment

    • anthonette50
      New Member
      • Mar 2008
      • 2

      #3
      Thanks, its a lot clearer now.

      Comment

      • BigDaddyLH
        Recognized Expert Top Contributor
        • Dec 2007
        • 1216

        #4
        Originally posted by anthonette50
        Thanks, its a lot clearer now.
        There are places where using StringBuilder to accumulate a String makes sense -- where you have a loop, for example, or where the code is spread through methods, so you create and pass the StringBuilder around. It has its uses, but your example was too simple.

        Comment

        • JosAH
          Recognized Expert MVP
          • Mar 2007
          • 11453

          #5
          While we're at it, a StringBuffer is to a StringBuilder as a Vector is to an ArrayList.
          Use a StringBuilder instead if you have to use a mutable string notion. All those
          silly synchronized StringBuffer methods aren't needed most of the time.

          kind regards,

          Jos

          Comment

          Working...