user1965081
user1965081

Reputation: 55

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?

Upvotes: 4

Views: 11642

Answers (7)

Pawananjay
Pawananjay

Reputation: 1

For getting synchronized version of string recommended to use StringBuffer where thread-safety is high required . For non-synchronized use StringBuilder class where thread-safety is not required and our application will give better performance ..

Upvotes: 0

Brigham
Brigham

Reputation: 14524

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);
}

Upvotes: 7

Farhan Syed
Farhan Syed

Reputation: 326

Yes you can. Like everyone pointed out, StringBuffer.toString() will flush out the contents as a String. The question you need to ask yourself is, do you really care about what you use or do you specifically want to use StringBuffer to learn something.

For your operation, one is as good as the other. If you really want to do what your friend tells you, I think folks here have answered it clearly.

Or you can tell your friend, "It doesn't matter. One is as good as the other in my case" :)

Upvotes: 0

phippsnatch
phippsnatch

Reputation: 186

You probably want something like:

  public static void winner ()
  {
      StringBuffer sb = new StringBuffer("THE WINNER IS ");

      if (position1 >= 100)
          System.out.println(sb.append(name1).toString());
      else if (position2 >= 100)
          System.out.println(sb.append(name2).toString());
  }

BUT generally StringBuilder is preferred to StringBuffer as access to StringBuffer is synchronized.

Upvotes: 3

AlexWien
AlexWien

Reputation: 28727

The idea of using StringBuffer or StringBuilder is to avoid repeated concatenation of Strings as showed below:

String result = "";
for (int i = 0; i < 200; i++) {
    result = result + i + ",";
}

This is not efficient, in each loop one String object is (java internally) created

Using StringBuilder / StringBuffer:

StringBuilder buf = new StringBuilder(200); // init with a estimation of length has advantage
for (int i = 0; i < 200; i++) {
    buf.append(i).append(",");
}
String result = buf.toString();

This avoids unneeded creation of strings in each loop, it simply fills up the buffer with characters, and resize the buffer if needed.

However in your case it is not worth the effort.

Upvotes: 1

asgoth
asgoth

Reputation: 35829

You can, since System.out.println will convert its argument to a String automatically, hence resulting the content of the StringBuffer. Mostly you will use it when you need to iterate a set of data.

With the append method, you can append data to the buffer:

String[] values = { 'string value', 'testing' };
StringBuffer sb = new StringBuffer();
for(String value: values) {
    sb.append(value);
}

will result in --> string valuetesting

Note: It might be better to consider StringBuilder instead.

Upvotes: 1

Jesus Ramos
Jesus Ramos

Reputation: 23268

Small string appends and concats typically don't see much of a gain from using StringBuilder but just keep in mind that a string append has 3 operations, 1 new allocation consisting of the size of both strings added, and 2 copy operations to copy the contents (which means you now have 3 strings in memory), with StringBuilder you just append and resize to a fixed width buffer which only requires 1 copy most of the time (amortized cost copy, sometimes you need to resize which takes 2). If you are appending a lot into 1 string I would recommend using StringBuilder instead but for concatentations like yours you should not see a loss in performance (measurable at least).

Upvotes: 1

Related Questions