How is StringBuffer used with .append

user1965081 picture user1965081 · Jan 11, 2013 · Viewed 11.1k times · Source

I'm doing a computer science project and I need to incorporate StringBuffers. I need help with what .append does and what concatenate means. Somebody told me I can show who is the winner (of my game) by using .append with StringBuffer.

  public static void winner ()
  {
    if (position1 >= 100){
      System.out.println("THE WINNER IS " + name1); 
    }
    else if (position2 >= 100){
      System.out.println("THE WINNER IS " + name2); 
    }
  }

Instead of having name as strings, can I use StringBuffer to output who won the game?

Answer

Brigham picture Brigham · Jan 11, 2013

Thanks to the compiler, you are already using StringBuilder which is the newer, faster version of StringBuffer.

Your code above will compile to the equivalent of:

public static void winner ()
{
  if (position1 >= 100){
    System.out.println(new StringBuilder("THE WINNER IS ").append(name1).toString()); 
  }
  else if (position2 >= 100){
    System.out.println(new StringBuilder("THE WINNER IS ").append(name2).toString()); 
  }
}

So, in this case, you would not be accomplishing anything that isn't already being done for you. Use StringBuilder when you are building a String in a loop.

In your situation, they were probably talking about pre-initializing a single StringBuilder for both cases:

public static void winner() {
  StringBuilder out = new StringBuilder("THE WINNER IS ");
  if (position1 >= 100) {
    out.append(name1);
  } else if (position2 >= 100 {
    out.append(name2);
  } else {
    return; // Preserve previous behavior just in case, remove this if it's not needed
  }
  System.out.println(out);
}