Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is StringBuffer used with .append

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?

like image 494
user1965081 Avatar asked Dec 11 '22 18:12

user1965081


1 Answers

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);
}
like image 145
Brigham Avatar answered Dec 31 '22 04:12

Brigham